1
0
Fork 0

Codechange: Reformat all sources.

pull/14042/head
frosch 2025-04-19 22:34:42 +02:00
parent 928a388a65
commit 0859d0393e
1115 changed files with 38704 additions and 31312 deletions

View File

@ -137,6 +137,7 @@ public:
/** Wrapper function for AIScanner::HasAI */
static bool HasAI(const ContentInfo &ci, bool md5sum);
static bool HasAILibrary(const ContentInfo &ci, bool md5sum);
private:
static uint frame_counter; ///< Tick counter for the AI code
static std::unique_ptr<AIScannerInfo> scanner_info; ///< ScriptScanner instance that is used to find AIs

View File

@ -8,11 +8,13 @@
/** @file ai_config.cpp Implementation of AIConfig. */
#include "../stdafx.h"
#include "ai_config.hpp"
#include "../company_base.h"
#include "../settings_type.h"
#include "../string_func.h"
#include "ai.hpp"
#include "ai_config.hpp"
#include "ai_info.hpp"
#include "../safeguards.h"

View File

@ -10,8 +10,8 @@
#ifndef AI_CONFIG_HPP
#define AI_CONFIG_HPP
#include "../script/script_config.hpp"
#include "../company_type.h"
#include "../script/script_config.hpp"
class AIConfig : public ScriptConfig {
public:
@ -20,13 +20,9 @@ public:
*/
static AIConfig *GetConfig(CompanyID company, ScriptSettingSource source = SSS_DEFAULT);
AIConfig() :
ScriptConfig()
{}
AIConfig() : ScriptConfig() {}
AIConfig(const AIConfig &config) :
ScriptConfig(config)
{}
AIConfig(const AIConfig &config) : ScriptConfig(config) {}
class AIInfo *GetInfo() const;

View File

@ -8,18 +8,19 @@
/** @file ai_core.cpp Implementation of AI. */
#include "../stdafx.h"
#include "../core/backup_type.hpp"
#include "../core/bitmath_func.hpp"
#include "../company_base.h"
#include "../company_func.h"
#include "../framerate_type.h"
#include "../network/network.h"
#include "../window_func.h"
#include "../framerate_type.h"
#include "ai_scanner.hpp"
#include "ai_instance.hpp"
#include "ai.hpp"
#include "ai_config.hpp"
#include "ai_info.hpp"
#include "ai.hpp"
#include "ai_instance.hpp"
#include "ai_scanner.hpp"
#include "../safeguards.h"
@ -353,4 +354,3 @@
{
return AI::scanner_library.get();
}

View File

@ -8,25 +8,25 @@
/** @file ai_gui.cpp %Window for configuring the AIs */
#include "../stdafx.h"
#include "../error.h"
#include "../company_base.h"
#include "../window_func.h"
#include "../network/network.h"
#include "../settings_func.h"
#include "../network/network_content.h"
#include "../core/geometry_func.hpp"
#include "ai.hpp"
#include "ai_gui.hpp"
#include "../core/geometry_func.hpp"
#include "../company_base.h"
#include "../error.h"
#include "../network/network.h"
#include "../network/network_content.h"
#include "../script/script_gui.h"
#include "../settings_func.h"
#include "../window_func.h"
#include "ai.hpp"
#include "ai_config.hpp"
#include "ai_info.hpp"
#include "../script/script_gui.h"
#include "table/strings.h"
#include "../safeguards.h"
/** Widgets for the configure AI window. */
/* clang-format off */
static constexpr NWidgetPart _nested_ai_config_widgets[] = {
@ -85,12 +85,7 @@ static constexpr NWidgetPart _nested_ai_config_widgets[] = {
/* clang-format on */
/** Window definition for the configure AI window. */
static WindowDesc _ai_config_desc(
WDP_CENTER, nullptr, 0, 0,
WC_GAME_OPTIONS, WC_NONE,
{},
_nested_ai_config_widgets
);
static WindowDesc _ai_config_desc(WDP_CENTER, nullptr, 0, 0, WC_GAME_OPTIONS, WC_NONE, {}, _nested_ai_config_widgets);
/**
* Window to configure which AIs will start.
@ -338,4 +333,3 @@ void ShowAIConfigWindow()
CloseWindowByClass(WC_GAME_OPTIONS);
new AIConfigWindow();
}

View File

@ -9,12 +9,13 @@
#include "../stdafx.h"
#include "../script/squirrel_class.hpp"
#include "ai_info.hpp"
#include "ai_scanner.hpp"
#include "../debug.h"
#include "../string_func.h"
#include "../rev.h"
#include "../script/squirrel_class.hpp"
#include "../string_func.h"
#include "ai_scanner.hpp"
#include "../safeguards.h"
@ -27,7 +28,12 @@ static bool CheckAPIVersion(const std::string &api_version)
return std::ranges::find(AIInfo::ApiVersions, api_version) != std::end(AIInfo::ApiVersions);
}
template <> SQInteger PushClassName<AIInfo, ScriptType::AI>(HSQUIRRELVM vm) { sq_pushstring(vm, "AIInfo", -1); return 1; }
template <>
SQInteger PushClassName<AIInfo, ScriptType::AI>(HSQUIRRELVM vm)
{
sq_pushstring(vm, "AIInfo", -1);
return 1;
}
/* static */ void AIInfo::RegisterAPI(Squirrel *engine)
{
@ -111,11 +117,7 @@ template <> SQInteger PushClassName<AIInfo, ScriptType::AI>(HSQUIRRELVM vm) { sq
return 0;
}
AIInfo::AIInfo() :
min_loadable_version(0),
use_as_random(false)
{
}
AIInfo::AIInfo() : min_loadable_version(0), use_as_random(false) {}
bool AIInfo::CanLoadFromVersion(int version) const
{
@ -123,7 +125,6 @@ bool AIInfo::CanLoadFromVersion(int version) const
return version >= this->min_loadable_version && version <= this->GetVersion();
}
/* static */ void AILibrary::RegisterAPI(Squirrel *engine)
{
/* Create the AILibrary class, and add the RegisterLibrary function */

View File

@ -43,12 +43,18 @@ public:
/**
* Use this AI as a random AI.
*/
bool UseAsRandomAI() const { return this->use_as_random; }
bool UseAsRandomAI() const
{
return this->use_as_random;
}
/**
* Get the API version this AI is written for.
*/
const std::string &GetAPIVersion() const { return this->api_version; }
const std::string &GetAPIVersion() const
{
return this->api_version;
}
private:
int min_loadable_version; ///< The AI can load savegame data if the version is equal or greater than this.
@ -74,7 +80,10 @@ public:
/**
* Get the category this library is in.
*/
const std::string &GetCategory() const { return this->category; }
const std::string &GetCategory() const
{
return this->category;
}
private:
std::string category; ///< The category this library is in.

View File

@ -8,21 +8,20 @@
/** @file ai_instance.cpp Implementation of AIInstance. */
#include "../stdafx.h"
#include "../debug.h"
#include "../error.h"
#include "ai_instance.hpp"
#include "../company_base.h"
#include "../company_func.h"
#include "../script/squirrel_class.hpp"
#include "ai_config.hpp"
#include "ai.hpp"
#include "../script/script_storage.hpp"
#include "../debug.h"
#include "../error.h"
#include "../script/script_cmd.h"
#include "../script/script_gui.h"
#include "../script/script_storage.hpp"
#include "../script/squirrel_class.hpp"
#include "ai.hpp"
#include "ai_config.hpp"
#include "ai_info.hpp"
#include "ai_instance.hpp"
#include "table/strings.h"
@ -34,9 +33,7 @@
#include "../safeguards.h"
AIInstance::AIInstance() :
ScriptInstance("AI")
{}
AIInstance::AIInstance() : ScriptInstance("AI") {}
void AIInstance::Initialize(AIInfo *info)
{

View File

@ -8,25 +8,22 @@
/** @file ai_scanner.cpp allows scanning AI scripts */
#include "../stdafx.h"
#include "ai_scanner.hpp"
#include <ranges>
#include "../core/random_func.hpp"
#include "../debug.h"
#include "../network/network.h"
#include "../openttd.h"
#include "../core/random_func.hpp"
#include "../script/squirrel_class.hpp"
#include "../script/api/script_object.hpp"
#include "../script/squirrel_class.hpp"
#include "ai_info.hpp"
#include "ai_scanner.hpp"
#include "../safeguards.h"
AIScannerInfo::AIScannerInfo() :
ScriptScanner(),
info_dummy(nullptr)
{
}
AIScannerInfo::AIScannerInfo() : ScriptScanner(), info_dummy(nullptr) {}
void AIScannerInfo::Initialize()
{
@ -67,7 +64,9 @@ AIInfo *AIScannerInfo::SelectRandomAI() const
}
/* Filter for AIs suitable as Random AI. */
auto random_ais = info_single_list | std::views::filter([](const auto &item) { return static_cast<AIInfo *>(item.second)->UseAsRandomAI(); });
auto random_ais = info_single_list | std::views::filter([](const auto &item) {
return static_cast<AIInfo *>(item.second)->UseAsRandomAI();
});
uint num_random_ais = std::ranges::distance(random_ais);
if (num_random_ais == 0) {
@ -119,7 +118,6 @@ AIInfo *AIScannerInfo::FindInfo(const std::string &name, int version, bool force
return info;
}
void AIScannerLibrary::Initialize()
{
ScriptScanner::Initialize("AIScanner");

View File

@ -41,9 +41,22 @@ public:
protected:
std::string GetScriptName(ScriptInfo *info) override;
const char *GetFileName() const override { return PATHSEP "info.nut"; }
Subdirectory GetDirectory() const override { return AI_DIR; }
const char *GetScannerName() const override { return "AIs"; }
const char *GetFileName() const override
{
return PATHSEP "info.nut";
}
Subdirectory GetDirectory() const override
{
return AI_DIR;
}
const char *GetScannerName() const override
{
return "AIs";
}
void RegisterAPI(class Squirrel *engine) override;
private:
@ -64,9 +77,22 @@ public:
protected:
std::string GetScriptName(ScriptInfo *info) override;
const char *GetFileName() const override { return PATHSEP "library.nut"; }
Subdirectory GetDirectory() const override { return AI_LIBRARY_DIR; }
const char *GetScannerName() const override { return "AI Libraries"; }
const char *GetFileName() const override
{
return PATHSEP "library.nut";
}
Subdirectory GetDirectory() const override
{
return AI_LIBRARY_DIR;
}
const char *GetScannerName() const override
{
return "AI Libraries";
}
void RegisterAPI(class Squirrel *engine) override;
};

View File

@ -84,18 +84,48 @@ struct Aircraft final : public SpecializedVehicle<Aircraft, VEH_AIRCRAFT> {
/** We don't want GCC to zero our struct! It already is zeroed and has an index! */
Aircraft() : SpecializedVehicleBase() {}
/** We want to 'destruct' the right class. */
virtual ~Aircraft() { this->PreDestructor(); }
virtual ~Aircraft()
{
this->PreDestructor();
}
void MarkDirty() override;
void UpdateDeltaXY() override;
ExpensesType GetExpenseType(bool income) const override { return income ? EXPENSES_AIRCRAFT_REVENUE : EXPENSES_AIRCRAFT_RUN; }
bool IsPrimaryVehicle() const override { return this->IsNormalAircraft(); }
ExpensesType GetExpenseType(bool income) const override
{
return income ? EXPENSES_AIRCRAFT_REVENUE : EXPENSES_AIRCRAFT_RUN;
}
bool IsPrimaryVehicle() const override
{
return this->IsNormalAircraft();
}
void GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const override;
int GetDisplaySpeed() const override { return this->cur_speed; }
int GetDisplayMaxSpeed() const override { return this->vcache.cached_max_speed; }
int GetSpeedOldUnits() const { return this->vcache.cached_max_speed * 10 / 128; }
int GetCurrentMaxSpeed() const override { return this->GetSpeedOldUnits(); }
int GetDisplaySpeed() const override
{
return this->cur_speed;
}
int GetDisplayMaxSpeed() const override
{
return this->vcache.cached_max_speed;
}
int GetSpeedOldUnits() const
{
return this->vcache.cached_max_speed * 10 / 128;
}
int GetCurrentMaxSpeed() const override
{
return this->GetSpeedOldUnits();
}
Money GetRunningCost() const override;
bool IsInDepot() const override
@ -109,7 +139,12 @@ struct Aircraft final : public SpecializedVehicle<Aircraft, VEH_AIRCRAFT> {
void OnNewEconomyDay() override;
uint Crash(bool flooded = false) override;
TileIndex GetOrderStationLocation(StationID station) override;
TileIndex GetCargoTile() const override { return this->First()->tile; }
TileIndex GetCargoTile() const override
{
return this->First()->tile;
}
ClosestDepot FindClosestDepot() override;
/**

View File

@ -11,36 +11,38 @@
*/
#include "stdafx.h"
#include "aircraft_cmd.h"
#include "core/backup_type.hpp"
#include "core/random_func.hpp"
#include "ai/ai.hpp"
#include "aircraft.h"
#include "cheat_type.h"
#include "command_func.h"
#include "company_base.h"
#include "company_func.h"
#include "disaster_vehicle.h"
#include "effectvehicle_func.h"
#include "engine_base.h"
#include "error_func.h"
#include "framerate_type.h"
#include "game/game.hpp"
#include "landscape.h"
#include "news_func.h"
#include "newgrf_airporttiles.h"
#include "newgrf_engine.h"
#include "newgrf_sound.h"
#include "news_func.h"
#include "sound_func.h"
#include "spritecache.h"
#include "error_func.h"
#include "station_base.h"
#include "strings_func.h"
#include "command_func.h"
#include "window_func.h"
#include "timer/timer_game_calendar.h"
#include "timer/timer_game_economy.h"
#include "vehicle_func.h"
#include "sound_func.h"
#include "cheat_type.h"
#include "company_base.h"
#include "ai/ai.hpp"
#include "game/game.hpp"
#include "company_func.h"
#include "effectvehicle_func.h"
#include "station_base.h"
#include "engine_base.h"
#include "core/random_func.hpp"
#include "core/backup_type.hpp"
#include "zoom_func.h"
#include "disaster_vehicle.h"
#include "newgrf_airporttiles.h"
#include "framerate_type.h"
#include "aircraft_cmd.h"
#include "vehicle_cmd.h"
#include "vehicle_func.h"
#include "window_func.h"
#include "zoom_func.h"
#include "table/strings.h"
@ -54,12 +56,14 @@ void Aircraft::UpdateDeltaXY()
this->y_extent = 2;
switch (this->subtype) {
default: NOT_REACHED();
default:
NOT_REACHED();
case AIR_AIRCRAFT:
case AIR_HELICOPTER:
switch (this->state) {
default: break;
default:
break;
case ENDTAKEOFF:
case LANDING:
case HELILANDING:
@ -90,15 +94,8 @@ static bool AirportFindFreeTerminal(Aircraft *v, const AirportFTAClass *apc);
static bool AirportFindFreeHelipad(Aircraft *v, const AirportFTAClass *apc);
static void CrashAirplane(Aircraft *v);
static const SpriteID _aircraft_sprite[] = {
0x0EB5, 0x0EBD, 0x0EC5, 0x0ECD,
0x0ED5, 0x0EDD, 0x0E9D, 0x0EA5,
0x0EAD, 0x0EE5, 0x0F05, 0x0F0D,
0x0F15, 0x0F1D, 0x0F25, 0x0F2D,
0x0EED, 0x0EF5, 0x0EFD, 0x0F35,
0x0E9D, 0x0EA5, 0x0EAD, 0x0EB5,
0x0EBD, 0x0EC5
};
static const SpriteID _aircraft_sprite[] = {0x0EB5, 0x0EBD, 0x0EC5, 0x0ECD, 0x0ED5, 0x0EDD, 0x0E9D, 0x0EA5, 0x0EAD, 0x0EE5, 0x0F05, 0x0F0D, 0x0F15, 0x0F1D, 0x0F25, 0x0F2D, 0x0EED, 0x0EF5, 0x0EFD,
0x0F35, 0x0E9D, 0x0EA5, 0x0EAD, 0x0EB5, 0x0EBD, 0x0EC5};
template <>
bool IsValidImageIndex<VEH_AIRCRAFT>(uint8_t image_index)
@ -133,8 +130,7 @@ static StationID FindNearestHangar(const Aircraft *v)
const Station *last_dest = nullptr;
const Station *next_dest = nullptr;
if (max_range != 0) {
if (v->current_order.IsType(OT_GOTO_STATION) ||
(v->current_order.IsType(OT_GOTO_DEPOT) && (v->current_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) == 0)) {
if (v->current_order.IsType(OT_GOTO_STATION) || (v->current_order.IsType(OT_GOTO_DEPOT) && (v->current_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) == 0)) {
last_dest = Station::GetIfValid(v->last_station_visited);
next_dest = Station::GetIfValid(v->current_order.GetDestination().ToStationID());
} else {
@ -223,9 +219,7 @@ void DrawAircraftEngine(int left, int right, int preferred_x, int y, EngineID en
Rect rect;
seq.GetBounds(&rect);
preferred_x = Clamp(preferred_x,
left - UnScaleGUI(rect.left),
right - UnScaleGUI(rect.right));
preferred_x = Clamp(preferred_x, left - UnScaleGUI(rect.left), right - UnScaleGUI(rect.right));
seq.Draw(preferred_x, y, pal, pal == PALETTE_CRASH);
@ -395,7 +389,6 @@ CommandCost CmdBuildAircraft(DoCommandFlags flags, TileIndex tile, const Engine
return CommandCost();
}
ClosestDepot Aircraft::FindClosestDepot()
{
const Station *st = GetTargetAirportIfValid(this);
@ -593,7 +586,6 @@ static void PlayAircraftSound(const Vehicle *v)
}
}
/**
* Update cached values of an aircraft.
* Currently caches callback 36 max speed.
@ -626,7 +618,6 @@ void UpdateAircraftCache(Aircraft *v, bool update_range)
}
}
/**
* Special velocities for aircraft
*/
@ -743,7 +734,8 @@ void GetAircraftFlightLevelBounds(const Vehicle *v, int *min_level, int *max_lev
base_altitude += 10;
break;
default: break;
default:
break;
}
/* Make faster planes fly higher so that they can overtake slower ones */
@ -782,15 +774,13 @@ int GetAircraftFlightLevel(T *v, bool takeoff)
assert(aircraft_middle_altitude < aircraft_max_altitude);
int z = v->z_pos;
if (z < aircraft_min_altitude ||
(HasBit(v->flags, VAF_IN_MIN_HEIGHT_CORRECTION) && z < aircraft_middle_altitude)) {
if (z < aircraft_min_altitude || (HasBit(v->flags, VAF_IN_MIN_HEIGHT_CORRECTION) && z < aircraft_middle_altitude)) {
/* Ascend. And don't fly into that mountain right ahead.
* And avoid our aircraft become a stairclimber, so if we start
* correcting altitude, then we stop correction not too early. */
SetBit(v->flags, VAF_IN_MIN_HEIGHT_CORRECTION);
z += takeoff ? 2 : 1;
} else if (!takeoff && (z > aircraft_max_altitude ||
(HasBit(v->flags, VAF_IN_MAX_HEIGHT_CORRECTION) && z > aircraft_middle_altitude))) {
} else if (!takeoff && (z > aircraft_max_altitude || (HasBit(v->flags, VAF_IN_MAX_HEIGHT_CORRECTION) && z > aircraft_middle_altitude))) {
/* Descend lower. You are an aircraft, not an space ship.
* And again, don't stop correcting altitude too early. */
SetBit(v->flags, VAF_IN_MAX_HEIGHT_CORRECTION);
@ -854,7 +844,6 @@ static uint8_t AircraftGetEntryPoint(const Aircraft *v, const AirportFTAClass *a
return apc->entry_points[dir];
}
static void MaybeCrashAirplane(Aircraft *v);
/**
@ -1024,9 +1013,18 @@ static bool AircraftController(Aircraft *v)
bool hard_limit = true;
if (amd.flags.Test(AirportMovingDataFlag::NoSpeedClamp)) speed_limit = SPEED_LIMIT_NONE;
if (amd.flags.Test(AirportMovingDataFlag::Hold)) { speed_limit = SPEED_LIMIT_HOLD; hard_limit = false; }
if (amd.flags.Test(AirportMovingDataFlag::Land)) { speed_limit = SPEED_LIMIT_APPROACH; hard_limit = false; }
if (amd.flags.Test(AirportMovingDataFlag::Brake)) { speed_limit = SPEED_LIMIT_TAXI; hard_limit = false; }
if (amd.flags.Test(AirportMovingDataFlag::Hold)) {
speed_limit = SPEED_LIMIT_HOLD;
hard_limit = false;
}
if (amd.flags.Test(AirportMovingDataFlag::Land)) {
speed_limit = SPEED_LIMIT_APPROACH;
hard_limit = false;
}
if (amd.flags.Test(AirportMovingDataFlag::Brake)) {
speed_limit = SPEED_LIMIT_TAXI;
hard_limit = false;
}
int count = UpdateAircraftSpeed(v, speed_limit, hard_limit);
if (count == 0) return false;
@ -1041,23 +1039,17 @@ static bool AircraftController(Aircraft *v)
if (v->turn_counter != 0) v->turn_counter--;
do {
GetNewVehiclePosResult gp;
if (nudge_towards_target || amd.flags.Test(AirportMovingDataFlag::Land)) {
/* move vehicle one pixel towards target */
gp.x = (v->x_pos != (x + amd.x)) ?
v->x_pos + ((x + amd.x > v->x_pos) ? 1 : -1) :
v->x_pos;
gp.y = (v->y_pos != (y + amd.y)) ?
v->y_pos + ((y + amd.y > v->y_pos) ? 1 : -1) :
v->y_pos;
gp.x = (v->x_pos != (x + amd.x)) ? v->x_pos + ((x + amd.x > v->x_pos) ? 1 : -1) : v->x_pos;
gp.y = (v->y_pos != (y + amd.y)) ? v->y_pos + ((y + amd.y > v->y_pos) ? 1 : -1) : v->y_pos;
/* Oilrigs must keep v->tile as st->airport.tile, since the landing pad is in a non-airport tile */
gp.new_tile = (st->airport.type == AT_OILRIG) ? st->airport.tile : TileVirtXY(gp.x, gp.y);
} else {
/* Turn. Do it slowly if in the air. */
Direction newdir = GetDirectionTowards(v, x + amd.x, y + amd.y);
if (newdir != v->direction) {
@ -1149,13 +1141,11 @@ static bool AircraftController(Aircraft *v)
/* We've landed. Decrease speed when we're reaching end of runway. */
if (amd.flags.Test(AirportMovingDataFlag::Brake)) {
if (z > airport_z) {
z--;
} else if (z < airport_z) {
z++;
}
}
SetAircraftPosition(v, gp.x, gp.y, z);
@ -1189,18 +1179,12 @@ static bool HandleCrashedAircraft(Aircraft *v)
if (v->crashed_counter < 650) {
uint32_t r;
if (Chance16R(1, 32, r)) {
static const DirDiff delta[] = {
DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
};
static const DirDiff delta[] = {DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT};
v->direction = ChangeDir(v->direction, delta[GB(r, 16, 2)]);
SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
r = Random();
CreateEffectVehicleRel(v,
GB(r, 0, 4) - 4,
GB(r, 4, 4) - 4,
GB(r, 8, 4),
EV_EXPLOSION_SMALL);
CreateEffectVehicleRel(v, GB(r, 0, 4) - 4, GB(r, 4, 4) - 4, GB(r, 8, 4), EV_EXPLOSION_SMALL);
}
} else if (v->crashed_counter >= 10000) {
/* remove rubble of crashed airplane */
@ -1222,7 +1206,6 @@ static bool HandleCrashedAircraft(Aircraft *v)
return true;
}
/**
* Handle smoke of broken aircraft.
* @param v Aircraft
@ -1233,16 +1216,7 @@ static void HandleAircraftSmoke(Aircraft *v, bool mode)
static const struct {
int8_t x;
int8_t y;
} smoke_pos[] = {
{ 5, 5 },
{ 6, 0 },
{ 5, -5 },
{ 0, -6 },
{ -5, -5 },
{ -6, 0 },
{ -5, 5 },
{ 0, 6 }
};
} smoke_pos[] = {{5, 5}, {6, 0}, {5, -5}, {0, -6}, {-5, -5}, {-6, 0}, {-5, 5}, {0, 6}};
if (!v->vehstatus.Test(VehState::AircraftBroken)) return;
@ -1255,12 +1229,7 @@ static void HandleAircraftSmoke(Aircraft *v, bool mode)
/* Spawn effect et most once per Tick, i.e. !mode */
if (!mode && (v->tick_counter & 0x0F) == 0) {
CreateEffectVehicleRel(v,
smoke_pos[v->direction].x,
smoke_pos[v->direction].y,
2,
EV_BREAKDOWN_SMOKE_AIRCRAFT
);
CreateEffectVehicleRel(v, smoke_pos[v->direction].x, smoke_pos[v->direction].y, 2, EV_BREAKDOWN_SMOKE_AIRCRAFT);
}
}
@ -1293,7 +1262,6 @@ void HandleMissingAircraftOrders(Aircraft *v)
}
}
TileIndex Aircraft::GetOrderStationLocation(StationID)
{
/* Orders are changed in flight, ensure going to the right station. */
@ -1314,7 +1282,6 @@ void Aircraft::MarkDirty()
}
}
uint Aircraft::Crash(bool flooded)
{
uint victims = Vehicle::Crash(flooded) + 2; // pilots
@ -1345,8 +1312,10 @@ static void CrashAirplane(Aircraft *v)
headline = GetEncodedString(STR_NEWS_AIRCRAFT_CRASH, victims, st->index);
}
AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, vt, st == nullptr ? ScriptEventVehicleCrashed::CRASH_AIRCRAFT_NO_AIRPORT : ScriptEventVehicleCrashed::CRASH_PLANE_LANDING, victims, v->owner));
Game::NewEvent(new ScriptEventVehicleCrashed(v->index, vt, st == nullptr ? ScriptEventVehicleCrashed::CRASH_AIRCRAFT_NO_AIRPORT : ScriptEventVehicleCrashed::CRASH_PLANE_LANDING, victims, v->owner));
AI::NewEvent(v->owner,
new ScriptEventVehicleCrashed(v->index, vt, st == nullptr ? ScriptEventVehicleCrashed::CRASH_AIRCRAFT_NO_AIRPORT : ScriptEventVehicleCrashed::CRASH_PLANE_LANDING, victims, v->owner));
Game::NewEvent(
new ScriptEventVehicleCrashed(v->index, vt, st == nullptr ? ScriptEventVehicleCrashed::CRASH_AIRCRAFT_NO_AIRPORT : ScriptEventVehicleCrashed::CRASH_PLANE_LANDING, victims, v->owner));
NewsType newstype = NewsType::Accident;
if (v->owner != _local_company) {
@ -1365,13 +1334,10 @@ static void CrashAirplane(Aircraft *v)
*/
static void MaybeCrashAirplane(Aircraft *v)
{
Station *st = Station::Get(v->targetairport);
uint32_t prob;
if (st->airport.GetFTA()->flags.Test(AirportFTAClass::Flag::ShortStrip) &&
(AircraftVehInfo(v->engine_type)->subtype & AIR_FAST) &&
!_cheats.no_jetcrash.value) {
if (st->airport.GetFTA()->flags.Test(AirportFTAClass::Flag::ShortStrip) && (AircraftVehInfo(v->engine_type)->subtype & AIR_FAST) && !_cheats.no_jetcrash.value) {
prob = 3276;
} else {
if (_settings_game.vehicle.plane_crashes == 0) return;
@ -1405,12 +1371,7 @@ static void AircraftEntersTerminal(Aircraft *v)
if (!(st->had_vehicle_of_type & HVOT_AIRCRAFT)) {
st->had_vehicle_of_type |= HVOT_AIRCRAFT;
/* show newsitem of celebrating citizens */
AddVehicleNewsItem(
GetEncodedString(STR_NEWS_FIRST_AIRCRAFT_ARRIVAL, st->index),
(v->owner == _local_company) ? NewsType::ArrivalCompany : NewsType::ArrivalOther,
v->index,
st->index
);
AddVehicleNewsItem(GetEncodedString(STR_NEWS_FIRST_AIRCRAFT_ARRIVAL, st->index), (v->owner == _local_company) ? NewsType::ArrivalCompany : NewsType::ArrivalOther, v->index, st->index);
AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
}
@ -1437,7 +1398,6 @@ static void AircraftLandAirplane(Aircraft *v)
}
}
/** set the right pos when heading to other airports after takeoff */
void AircraftNextAirportPos_and_Order(Aircraft *v)
{
@ -1527,9 +1487,7 @@ static void AircraftEventHandler_InHangar(Aircraft *v, const AirportFTAClass *ap
/* Check if we should wait here for unbunching. */
if (v->IsWaitingForUnbunching()) return;
if (!v->current_order.IsType(OT_GOTO_STATION) &&
!v->current_order.IsType(OT_GOTO_DEPOT))
return;
if (!v->current_order.IsType(OT_GOTO_STATION) && !v->current_order.IsType(OT_GOTO_DEPOT)) return;
/* We are leaving a hangar, but have to go to the exact same one; re-enter */
if (v->current_order.IsType(OT_GOTO_DEPOT) && v->current_order.GetDestination() == v->targetairport) {
@ -1723,7 +1681,6 @@ static void AircraftEventHandler_EndLanding(Aircraft *v, const AirportFTAClass *
if (AirportFindFreeTerminal(v, apc)) return;
}
v->state = HANGAR;
}
static void AircraftEventHandler_HeliEndLanding(Aircraft *v, const AirportFTAClass *apc)
@ -2130,7 +2087,6 @@ bool Aircraft::Tick()
return true;
}
/**
* Returns aircraft's target station if v->target_airport
* is a valid station with airport.
@ -2164,8 +2120,7 @@ void UpdateAirplanesOnNewStation(const Station *st)
Order *o = &v->current_order;
/* The aircraft is heading to a hangar, but the new station doesn't have one,
* or the aircraft can't land on the new station. Cancel current order. */
if (o->IsType(OT_GOTO_DEPOT) && !(o->GetDepotOrderType() & ODTFB_PART_OF_ORDERS) && o->GetDestination() == st->index &&
(!st->airport.HasHangar() || !CanVehicleUseStation(v, st))) {
if (o->IsType(OT_GOTO_DEPOT) && !(o->GetDepotOrderType() & ODTFB_PART_OF_ORDERS) && o->GetDestination() == st->index && (!st->airport.HasHangar() || !CanVehicleUseStation(v, st))) {
o->MakeDummy();
SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
}

View File

@ -8,13 +8,14 @@
/** @file aircraft_gui.cpp The GUI of aircraft. */
#include "stdafx.h"
#include "aircraft.h"
#include "vehicle_gui.h"
#include "newgrf_engine.h"
#include "spritecache.h"
#include "strings_func.h"
#include "vehicle_func.h"
#include "vehicle_gui.h"
#include "window_gui.h"
#include "spritecache.h"
#include "zoom_func.h"
#include "table/strings.h"
@ -61,7 +62,6 @@ void DrawAircraftDetails(const Aircraft *v, const Rect &r)
DrawString(r.left, r.right, y, GetString(STR_VEHICLE_INFO_FEEDER_CARGO_VALUE, feeder_share));
}
/**
* Draws an image of an aircraft
* @param v Front vehicle

View File

@ -8,15 +8,15 @@
/** @file airport.cpp Functions related to airports. */
#include "stdafx.h"
#include "station_base.h"
#include "table/strings.h"
#include "table/airport_movement.h"
#include "table/airporttile_ids.h"
#include "table/strings.h"
#include "safeguards.h"
/**
* Define a generic airport.
* @param name Suffix of the names of the airport data.
@ -65,11 +65,9 @@ AIRPORT_GENERIC(dummy, nullptr, 0, AirportFTAClass::Flags({AirportFTAClass::Flag
#include "table/airport_defaults.h"
static uint16_t AirportGetNofElements(const AirportFTAbuildup *apFA);
static void AirportBuildAutomata(std::vector<AirportFTA> &layout, uint8_t nofelements, const AirportFTAbuildup *apFA);
/**
* Rotate the airport moving data to another rotation.
* @param orig Pointer to the moving data to rotate.
@ -104,27 +102,15 @@ AirportMovingData RotateAirportMovingData(const AirportMovingData *orig, Directi
amd.y = orig->x;
break;
default: NOT_REACHED();
default:
NOT_REACHED();
}
return amd;
}
AirportFTAClass::AirportFTAClass(
const AirportMovingData *moving_data_,
const uint8_t *terminals_,
const uint8_t num_helipads_,
const uint8_t *entry_points_,
Flags flags_,
const AirportFTAbuildup *apFA,
uint8_t delta_z_
) :
moving_data(moving_data_),
terminals(terminals_),
num_helipads(num_helipads_),
flags(flags_),
nofelements(AirportGetNofElements(apFA)),
entry_points(entry_points_),
delta_z(delta_z_)
const AirportMovingData *moving_data_, const uint8_t *terminals_, const uint8_t num_helipads_, const uint8_t *entry_points_, Flags flags_, const AirportFTAbuildup *apFA, uint8_t delta_z_) :
moving_data(moving_data_), terminals(terminals_), num_helipads(num_helipads_), flags(flags_), nofelements(AirportGetNofElements(apFA)), entry_points(entry_points_), delta_z(delta_z_)
{
/* Build the state machine itself */
AirportBuildAutomata(this->layout, this->nofelements, apFA);
@ -150,9 +136,7 @@ static uint16_t AirportGetNofElements(const AirportFTAbuildup *apFA)
return nofelements;
}
AirportFTA::AirportFTA(const AirportFTAbuildup &buildup) : blocks(buildup.blocks), position(buildup.position), next_position(buildup.next), heading(buildup.heading)
{
}
AirportFTA::AirportFTA(const AirportFTAbuildup &buildup) : blocks(buildup.blocks), position(buildup.position), next_position(buildup.next), heading(buildup.heading) {}
/**
* Construct the FTA given a description.

View File

@ -166,14 +166,7 @@ public:
using Flags = EnumBitSet<Flag, uint8_t>;
AirportFTAClass(
const AirportMovingData *moving_data,
const uint8_t *terminals,
const uint8_t num_helipads,
const uint8_t *entry_points,
Flags flags,
const AirportFTAbuildup *apFA,
uint8_t delta_z
);
const AirportMovingData *moving_data, const uint8_t *terminals, const uint8_t num_helipads, const uint8_t *entry_points, Flags flags, const AirportFTAbuildup *apFA, uint8_t delta_z);
/**
* Get movement data at a position.
@ -196,7 +189,6 @@ public:
uint8_t delta_z; ///< Z adjustment for helicopter pads
};
const AirportFTAClass *GetAirport(const uint8_t airport_type);
uint8_t GetVehiclePosOnBuild(TileIndex hangar_tile);

View File

@ -8,41 +8,40 @@
/** @file airport_gui.cpp The GUI for airports. */
#include "stdafx.h"
#include "economy_func.h"
#include "window_gui.h"
#include "station_gui.h"
#include "terraform_gui.h"
#include "sound_func.h"
#include "window_func.h"
#include "strings_func.h"
#include "viewport_func.h"
#include "company_func.h"
#include "tilehighlight_func.h"
#include "core/geometry_func.hpp"
#include "airport_cmd.h"
#include "command_func.h"
#include "company_base.h"
#include "station_type.h"
#include "company_func.h"
#include "dropdown_func.h"
#include "dropdown_type.h"
#include "economy_func.h"
#include "gui.h"
#include "hotkeys.h"
#include "newgrf_airport.h"
#include "newgrf_badge_gui.h"
#include "newgrf_callbacks.h"
#include "dropdown_type.h"
#include "dropdown_func.h"
#include "core/geometry_func.hpp"
#include "hotkeys.h"
#include "vehicle_func.h"
#include "gui.h"
#include "command_func.h"
#include "airport_cmd.h"
#include "sound_func.h"
#include "station_cmd.h"
#include "zoom_func.h"
#include "station_gui.h"
#include "station_type.h"
#include "strings_func.h"
#include "terraform_gui.h"
#include "tilehighlight_func.h"
#include "timer/timer.h"
#include "timer/timer_game_calendar.h"
#include "vehicle_func.h"
#include "viewport_func.h"
#include "window_func.h"
#include "window_gui.h"
#include "zoom_func.h"
#include "widgets/airport_widget.h"
#include "table/strings.h"
#include "safeguards.h"
static AirportClassID _selected_airport_class; ///< the currently visible airport class
static int _selected_airport_index; ///< the index of the selected airport in the current class or -1
static uint8_t _selected_airport_layout; ///< selected airport layout number.
@ -136,11 +135,11 @@ struct BuildAirToolbarWindow : Window {
this->last_user_action = widget;
break;
default: break;
default:
break;
}
}
void OnPlaceObject([[maybe_unused]] Point pt, TileIndex tile) override
{
switch (this->last_user_action) {
@ -152,7 +151,8 @@ struct BuildAirToolbarWindow : Window {
PlaceProc_DemolishArea(tile);
break;
default: NOT_REACHED();
default:
NOT_REACHED();
}
}
@ -191,10 +191,12 @@ struct BuildAirToolbarWindow : Window {
return w->OnHotkey(hotkey);
}
static inline HotkeyList hotkeys{"airtoolbar", {
static inline HotkeyList hotkeys{"airtoolbar",
{
Hotkey('1', "airport", WID_AT_AIRPORT),
Hotkey('2', "demolish", WID_AT_DEMOLISH),
}, AirportToolbarGlobalHotkeys};
},
AirportToolbarGlobalHotkeys};
};
/* clang-format off */
@ -212,13 +214,7 @@ static constexpr NWidgetPart _nested_air_toolbar_widgets[] = {
};
/* clang-format on */
static WindowDesc _air_toolbar_desc(
WDP_ALIGN_TOOLBAR, "toolbar_air", 0, 0,
WC_BUILD_TOOLBAR, WC_NONE,
WindowDefaultFlag::Construction,
_nested_air_toolbar_widgets,
&BuildAirToolbarWindow::hotkeys
);
static WindowDesc _air_toolbar_desc(WDP_ALIGN_TOOLBAR, "toolbar_air", 0, 0, WC_BUILD_TOOLBAR, WC_NONE, WindowDefaultFlag::Construction, _nested_air_toolbar_widgets, &BuildAirToolbarWindow::hotkeys);
/**
* Open the build airport toolbar window
@ -376,7 +372,8 @@ public:
}
break;
default: break;
default:
break;
}
}
@ -506,7 +503,8 @@ public:
break;
}
case WID_AP_BTN_DONTHILIGHT: case WID_AP_BTN_DOHILIGHT:
case WID_AP_BTN_DONTHILIGHT:
case WID_AP_BTN_DOHILIGHT:
_settings_client.gui.station_show_coverage = (widget != WID_AP_BTN_DONTHILIGHT);
this->SetWidgetLoweredState(WID_AP_BTN_DONTHILIGHT, !_settings_client.gui.station_show_coverage);
this->SetWidgetLoweredState(WID_AP_BTN_DOHILIGHT, _settings_client.gui.station_show_coverage);
@ -621,12 +619,7 @@ static constexpr NWidgetPart _nested_build_airport_widgets[] = {
};
/* clang-format on */
static WindowDesc _build_airport_desc(
WDP_AUTO, nullptr, 0, 0,
WC_BUILD_STATION, WC_BUILD_TOOLBAR,
WindowDefaultFlag::Construction,
_nested_build_airport_widgets
);
static WindowDesc _build_airport_desc(WDP_AUTO, nullptr, 0, 0, WC_BUILD_STATION, WC_BUILD_TOOLBAR, WindowDefaultFlag::Construction, _nested_build_airport_widgets);
static void ShowBuildAirportPicker(Window *parent)
{

View File

@ -8,11 +8,12 @@
/** @file animated_tile.cpp Everything related to animated tiles. */
#include "stdafx.h"
#include "animated_tile_func.h"
#include "animated_tile_map.h"
#include "framerate_type.h"
#include "tile_cmd.h"
#include "viewport_func.h"
#include "framerate_type.h"
#include "safeguards.h"

View File

@ -8,14 +8,15 @@
/** @file articulated_vehicles.cpp Implementation of articulated vehicles. */
#include "stdafx.h"
#include "core/bitmath_func.hpp"
#include "core/random_func.hpp"
#include "train.h"
#include "roadveh.h"
#include "vehicle_func.h"
#include "engine_func.h"
#include "company_func.h"
#include "engine_func.h"
#include "newgrf.h"
#include "roadveh.h"
#include "train.h"
#include "vehicle_func.h"
#include "table/strings.h"
@ -97,7 +98,6 @@ uint CountArticulatedParts(EngineID engine_type, bool purchase_window)
return i - 1;
}
/**
* Returns the default (non-refitted) cargo and capacity of a specific EngineID.
* @param engine the EngineID of interest
@ -355,7 +355,8 @@ void AddArticulatedParts(Vehicle *first)
const Engine *e_artic = Engine::Get(engine_type);
switch (type) {
default: NOT_REACHED();
default:
NOT_REACHED();
case VEH_TRAIN: {
Train *front = Train::From(first);

View File

@ -10,8 +10,8 @@
#ifndef ARTICULATED_VEHICLES_H
#define ARTICULATED_VEHICLES_H
#include "vehicle_type.h"
#include "engine_type.h"
#include "vehicle_type.h"
uint CountArticulatedParts(EngineID engine_type, bool purchase_window);
CargoArray GetCapacityOfArticulatedParts(EngineID engine);
@ -24,5 +24,4 @@ bool IsArticulatedVehicleRefittable(EngineID engine);
bool IsArticulatedEngine(EngineID engine_type);
void CheckConsistencyOfArticulatedVehicle(const Vehicle *v);
#endif /* ARTICULATED_VEHICLES_H */

View File

@ -12,8 +12,8 @@
#include "autocompletion.h"
#include "console_internal.h"
#include "town.h"
#include "network/network_base.h"
#include "town.h"
#include "safeguards.h"

View File

@ -30,6 +30,7 @@ public:
{
this->Reset();
}
virtual ~AutoCompletion() = default;
bool AutoComplete();

View File

@ -8,11 +8,12 @@
/** @file autoreplace.cpp Management of replacement lists. */
#include "stdafx.h"
#include "command_func.h"
#include "group.h"
#include "autoreplace_base.h"
#include "core/bitmath_func.hpp"
#include "core/pool_func.hpp"
#include "autoreplace_base.h"
#include "command_func.h"
#include "group.h"
#include "safeguards.h"

View File

@ -38,8 +38,9 @@ struct EngineRenew : EngineRenewPool::PoolItem<&_enginerenew_pool> {
bool replace_when_old = false; ///< Do replacement only when vehicle is old.
EngineRenew() {}
EngineRenew(EngineID from, EngineID to, GroupID group_id, bool replace_when_old, EngineRenew *next) :
from(from), to(to), next(next), group_id(group_id), replace_when_old(replace_when_old) {}
EngineRenew(EngineID from, EngineID to, GroupID group_id, bool replace_when_old, EngineRenew *next) : from(from), to(to), next(next), group_id(group_id), replace_when_old(replace_when_old) {}
~EngineRenew() {}
};

View File

@ -8,26 +8,28 @@
/** @file autoreplace_cmd.cpp Deals with autoreplace execution but not the setup */
#include "stdafx.h"
#include "company_func.h"
#include "train.h"
#include "command_func.h"
#include "engine_func.h"
#include "vehicle_func.h"
#include "autoreplace_func.h"
#include "autoreplace_gui.h"
#include "articulated_vehicles.h"
#include "autoreplace_cmd.h"
#include "core/bitmath_func.hpp"
#include "core/random_func.hpp"
#include "vehiclelist.h"
#include "road.h"
#include "ai/ai.hpp"
#include "news_func.h"
#include "strings_func.h"
#include "autoreplace_cmd.h"
#include "articulated_vehicles.h"
#include "autoreplace_func.h"
#include "autoreplace_gui.h"
#include "command_func.h"
#include "company_func.h"
#include "engine_func.h"
#include "group_cmd.h"
#include "news_func.h"
#include "order_cmd.h"
#include "road.h"
#include "strings_func.h"
#include "train.h"
#include "train_cmd.h"
#include "vehicle_cmd.h"
#include "vehicle_func.h"
#include "vehiclelist.h"
#include "table/strings.h"
@ -91,7 +93,8 @@ bool CheckAutoreplaceValidity(EngineID from, EngineID to, CompanyID company)
if ((e_from->u.air.subtype & AIR_CTOL) != (e_to->u.air.subtype & AIR_CTOL)) return false;
break;
default: break;
default:
break;
}
/* the engines needs to be able to carry the same cargo */
@ -340,16 +343,11 @@ static CommandCost BuildReplacementVehicle(Vehicle *old_veh, Vehicle **new_vehic
int order_id = GetIncompatibleRefitOrderIdForAutoreplace(old_veh, e);
if (order_id != -1) {
/* Orders contained a refit order that is incompatible with the new vehicle. */
headline = GetEncodedString(STR_NEWS_VEHICLE_AUTORENEW_FAILED,
old_veh_id,
STR_ERROR_AUTOREPLACE_INCOMPATIBLE_REFIT,
headline = GetEncodedString(STR_NEWS_VEHICLE_AUTORENEW_FAILED, old_veh_id, STR_ERROR_AUTOREPLACE_INCOMPATIBLE_REFIT,
order_id + 1); // 1-based indexing for display
} else {
/* Current cargo is incompatible with the new vehicle. */
headline = GetEncodedString(STR_NEWS_VEHICLE_AUTORENEW_FAILED,
old_veh_id,
STR_ERROR_AUTOREPLACE_INCOMPATIBLE_CARGO,
CargoSpec::Get(old_veh->cargo_type)->name);
headline = GetEncodedString(STR_NEWS_VEHICLE_AUTORENEW_FAILED, old_veh_id, STR_ERROR_AUTOREPLACE_INCOMPATIBLE_CARGO, CargoSpec::Get(old_veh->cargo_type)->name);
}
AddVehicleAdviceNewsItem(AdviceType::AutorenewFailed, std::move(headline), old_veh_id);
@ -358,7 +356,8 @@ static CommandCost BuildReplacementVehicle(Vehicle *old_veh, Vehicle **new_vehic
/* Build the new vehicle */
VehicleID new_veh_id;
std::tie(cost, new_veh_id, std::ignore, std::ignore, std::ignore) = Command<CMD_BUILD_VEHICLE>::Do({DoCommandFlag::Execute, DoCommandFlag::AutoReplace}, old_veh->tile, e, true, INVALID_CARGO, INVALID_CLIENT_ID);
std::tie(cost, new_veh_id, std::ignore, std::ignore, std::ignore) =
Command<CMD_BUILD_VEHICLE>::Do({DoCommandFlag::Execute, DoCommandFlag::AutoReplace}, old_veh->tile, e, true, INVALID_CARGO, INVALID_CLIENT_ID);
if (cost.Failed()) return cost;
Vehicle *new_veh = Vehicle::Get(new_veh_id);
@ -418,7 +417,8 @@ static CommandCost CopyHeadSpecificThings(Vehicle *old_head, Vehicle *new_head,
if (cost.Succeeded() && old_head != new_head) cost.AddCost(Command<CMD_CLONE_ORDER>::Do(DoCommandFlag::Execute, CO_SHARE, new_head->index, old_head->index));
/* Copy group membership */
if (cost.Succeeded() && old_head != new_head) cost.AddCost(std::get<0>(Command<CMD_ADD_VEHICLE_GROUP>::Do(DoCommandFlag::Execute, old_head->group_id, new_head->index, false, VehicleListIdentifier{})));
if (cost.Succeeded() && old_head != new_head)
cost.AddCost(std::get<0>(Command<CMD_ADD_VEHICLE_GROUP>::Do(DoCommandFlag::Execute, old_head->group_id, new_head->index, false, VehicleListIdentifier{})));
/* Perform start/stop check whether the new vehicle suits newgrf restrictions etc. */
if (cost.Succeeded()) {
@ -508,7 +508,10 @@ struct ReplaceChainItem {
* Get vehicle to use for this position.
* @return Either the new vehicle, or the old vehicle if there is no replacement.
*/
Vehicle *GetVehicle() const { return new_veh == nullptr ? old_veh : new_veh; }
Vehicle *GetVehicle() const
{
return new_veh == nullptr ? old_veh : new_veh;
}
};
/**
@ -852,4 +855,3 @@ CommandCost CmdSetAutoReplace(DoCommandFlags flags, GroupID id_g, EngineID old_e
return cost;
}

View File

@ -11,9 +11,9 @@
#define AUTOREPLACE_CMD_H
#include "command_type.h"
#include "vehicle_type.h"
#include "engine_type.h"
#include "group_type.h"
#include "vehicle_type.h"
CommandCost CmdAutoreplaceVehicle(DoCommandFlags flags, VehicleID veh_id);
CommandCost CmdSetAutoReplace(DoCommandFlags flags, GroupID id_g, EngineID old_engine_type, EngineID new_engine_type, bool when_old);

View File

@ -8,31 +8,31 @@
/** @file autoreplace_gui.cpp GUI for autoreplace handling. */
#include "stdafx.h"
#include "core/geometry_func.hpp"
#include "autoreplace_cmd.h"
#include "autoreplace_func.h"
#include "command_func.h"
#include "vehicle_gui.h"
#include "company_func.h"
#include "dropdown_func.h"
#include "dropdown_type.h"
#include "engine_base.h"
#include "engine_gui.h"
#include "group_cmd.h"
#include "newgrf_badge.h"
#include "newgrf_engine.h"
#include "rail.h"
#include "road.h"
#include "strings_func.h"
#include "window_func.h"
#include "autoreplace_func.h"
#include "company_func.h"
#include "engine_base.h"
#include "window_gui.h"
#include "engine_gui.h"
#include "settings_func.h"
#include "core/geometry_func.hpp"
#include "rail_gui.h"
#include "road.h"
#include "road_gui.h"
#include "dropdown_type.h"
#include "dropdown_func.h"
#include "autoreplace_cmd.h"
#include "group_cmd.h"
#include "settings_cmd.h"
#include "settings_func.h"
#include "strings_func.h"
#include "vehicle_gui.h"
#include "window_func.h"
#include "window_gui.h"
#include "widgets/autoreplace_widget.h"
#include "table/strings.h"
#include "safeguards.h"
@ -495,7 +495,8 @@ public:
ted.cost = 0;
ted.FillDefaultCapacities(e);
const Rect r = this->GetWidget<NWidgetBase>(side == 0 ? WID_RV_LEFT_DETAILS : WID_RV_RIGHT_DETAILS)->GetCurrentRect()
const Rect r = this->GetWidget<NWidgetBase>(side == 0 ? WID_RV_LEFT_DETAILS : WID_RV_RIGHT_DETAILS)
->GetCurrentRect()
.Shrink(WidgetDimensions::scaled.frametext, WidgetDimensions::scaled.framerect);
int text_end = DrawVehiclePurchaseInfo(r.left, r.right, r.top, this->sel_engine[side], ted);
needed_height = std::max(needed_height, (text_end - r.top) / GetCharacterHeight(FS_NORMAL));
@ -588,7 +589,10 @@ public:
const auto it = this->vscroll[click_side]->GetScrolledItemFromWidget(this->engines[click_side], pt.y, this, widget);
if (it != this->engines[click_side].end()) {
const auto &item = *it;
const Rect r = this->GetWidget<NWidgetBase>(widget)->GetCurrentRect().Shrink(WidgetDimensions::scaled.matrix).WithWidth(WidgetDimensions::scaled.hsep_indent * (item.indent + 1), _current_text_dir == TD_RTL);
const Rect r = this->GetWidget<NWidgetBase>(widget)
->GetCurrentRect()
.Shrink(WidgetDimensions::scaled.matrix)
.WithWidth(WidgetDimensions::scaled.hsep_indent * (item.indent + 1), _current_text_dir == TD_RTL);
if (item.flags.Test(EngineDisplayFlag::HasVariants) && IsInsideMM(r.left, r.right, pt.x)) {
/* toggle folded flag on engine */
assert(item.variant_id != EngineID::Invalid());
@ -604,8 +608,7 @@ public:
/* If Ctrl is pressed on the left side and we don't have any engines of the selected type, stop autoreplacing.
* This is most common when we have finished autoreplacing the engine and want to remove it from the list. */
if (click_side == 0 && _ctrl_pressed && e != EngineID::Invalid() &&
(GetGroupNumEngines(_local_company, sel_group, e) == 0 || GetGroupNumEngines(_local_company, ALL_GROUP, e) == 0)) {
if (click_side == 0 && _ctrl_pressed && e != EngineID::Invalid() && (GetGroupNumEngines(_local_company, sel_group, e) == 0 || GetGroupNumEngines(_local_company, ALL_GROUP, e) == 0)) {
EngineID veh_from = e;
Command<CMD_SET_AUTOREPLACE>::Post(this->sel_group, veh_from, EngineID::Invalid(), false);
break;
@ -758,12 +761,7 @@ static constexpr NWidgetPart _nested_replace_rail_vehicle_widgets[] = {
};
/* clang-format on */
static WindowDesc _replace_rail_vehicle_desc(
WDP_AUTO, "replace_vehicle_train", 500, 140,
WC_REPLACE_VEHICLE, WC_NONE,
WindowDefaultFlag::Construction,
_nested_replace_rail_vehicle_widgets
);
static WindowDesc _replace_rail_vehicle_desc(WDP_AUTO, "replace_vehicle_train", 500, 140, WC_REPLACE_VEHICLE, WC_NONE, WindowDefaultFlag::Construction, _nested_replace_rail_vehicle_widgets);
/* clang-format off */
static constexpr NWidgetPart _nested_replace_road_vehicle_widgets[] = {
@ -818,12 +816,7 @@ static constexpr NWidgetPart _nested_replace_road_vehicle_widgets[] = {
};
/* clang-format on */
static WindowDesc _replace_road_vehicle_desc(
WDP_AUTO, "replace_vehicle_road", 500, 140,
WC_REPLACE_VEHICLE, WC_NONE,
WindowDefaultFlag::Construction,
_nested_replace_road_vehicle_widgets
);
static WindowDesc _replace_road_vehicle_desc(WDP_AUTO, "replace_vehicle_road", 500, 140, WC_REPLACE_VEHICLE, WC_NONE, WindowDefaultFlag::Construction, _nested_replace_road_vehicle_widgets);
/* clang-format off */
static constexpr NWidgetPart _nested_replace_vehicle_widgets[] = {
@ -874,12 +867,7 @@ static constexpr NWidgetPart _nested_replace_vehicle_widgets[] = {
};
/* clang-format on */
static WindowDesc _replace_vehicle_desc(
WDP_AUTO, "replace_vehicle", 456, 118,
WC_REPLACE_VEHICLE, WC_NONE,
WindowDefaultFlag::Construction,
_nested_replace_vehicle_widgets
);
static WindowDesc _replace_vehicle_desc(WDP_AUTO, "replace_vehicle", 456, 118, WC_REPLACE_VEHICLE, WC_NONE, WindowDefaultFlag::Construction, _nested_replace_vehicle_widgets);
/**
* Show the autoreplace configuration window for a particular group.
@ -890,8 +878,14 @@ void ShowReplaceGroupVehicleWindow(GroupID id_g, VehicleType vehicletype)
{
CloseWindowById(WC_REPLACE_VEHICLE, vehicletype);
switch (vehicletype) {
case VEH_TRAIN: new ReplaceVehicleWindow(_replace_rail_vehicle_desc, vehicletype, id_g); break;
case VEH_ROAD: new ReplaceVehicleWindow(_replace_road_vehicle_desc, vehicletype, id_g); break;
default: new ReplaceVehicleWindow(_replace_vehicle_desc, vehicletype, id_g); break;
case VEH_TRAIN:
new ReplaceVehicleWindow(_replace_rail_vehicle_desc, vehicletype, id_g);
break;
case VEH_ROAD:
new ReplaceVehicleWindow(_replace_road_vehicle_desc, vehicletype, id_g);
break;
default:
new ReplaceVehicleWindow(_replace_vehicle_desc, vehicletype, id_g);
break;
}
}

View File

@ -51,8 +51,7 @@ inline bool AutoslopeCheckForEntranceEdge(TileIndex tile, int z_new, Slope tileh
inline bool AutoslopeCheckForAxis(TileIndex tile, int z_new, Slope tileh_new, Axis axis)
{
DiagDirection direction = AxisToDiagDir(axis);
return AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction) &&
AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction));
return AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction) && AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction));
}
/**
@ -64,9 +63,7 @@ inline bool AutoslopeCheckForAxis(TileIndex tile, int z_new, Slope tileh_new, Ax
*/
inline bool AutoslopeEnabled()
{
return (_settings_game.construction.autoslope &&
(_current_company < MAX_COMPANIES ||
(_current_company == OWNER_NONE && _game_mode == GM_EDITOR)));
return (_settings_game.construction.autoslope && (_current_company < MAX_COMPANIES || (_current_company == OWNER_NONE && _game_mode == GM_EDITOR)));
}
#endif /* AUTOSLOPE_H */

View File

@ -8,13 +8,14 @@
/** @file base_consist.cpp Properties for front vehicles/consists. */
#include "stdafx.h"
#include "base_consist.h"
#include "vehicle_base.h"
#include "string_func.h"
#include "vehicle_base.h"
#include "safeguards.h"
/**
* Copy properties of other BaseConsist.
* @param src Source for copying

View File

@ -10,11 +10,12 @@
#ifndef BASE_MEDIA_BASE_H
#define BASE_MEDIA_BASE_H
#include "fileio_func.h"
#include "textfile_type.h"
#include "textfile_gui.h"
#include "3rdparty/md5/md5.h"
#include <unordered_map>
#include "3rdparty/md5/md5.h"
#include "fileio_func.h"
#include "textfile_gui.h"
#include "textfile_type.h"
/* Forward declare these; can't do 'struct X' in functions as older GCCs barf on that */
struct IniFile;
@ -39,7 +40,8 @@ struct MD5File {
};
/** Defines the traits of a BaseSet type. */
template <class T> struct BaseSetTraits;
template <class T>
struct BaseSetTraits;
/**
* Information about a single base set.
@ -97,6 +99,7 @@ struct BaseSet {
}
bool FillSetDetails(const IniFile &ini, const std::string &path, const std::string &full_filename, bool allow_empty_filename = true);
void CopyCompatibleConfig([[maybe_unused]] const T &src) {}
/**
@ -177,6 +180,7 @@ protected:
* @return the extension
*/
static const char *GetExtension();
public:
/**
* Determine the graphics pack that has to be used.

View File

@ -11,9 +11,9 @@
#include "base_media_base.h"
#include "debug.h"
#include "error_func.h"
#include "ini_type.h"
#include "string_func.h"
#include "error_func.h"
extern void CheckExternalFiles();
@ -189,10 +189,8 @@ bool BaseMedia<Tbase_set>::AddFile(const std::string &filename, size_t basepath_
}
if (duplicate != nullptr) {
/* The more complete set takes precedence over the version number. */
if ((duplicate->valid_files == set->valid_files && duplicate->version >= set->version) ||
duplicate->valid_files > set->valid_files) {
Debug(grf, 1, "Not adding {} ({}) as base {} set (duplicate, {})", set->name, set->version,
BaseSet<Tbase_set>::SET_TYPE,
if ((duplicate->valid_files == set->valid_files && duplicate->version >= set->version) || duplicate->valid_files > set->valid_files) {
Debug(grf, 1, "Not adding {} ({}) as base {} set (duplicate, {})", set->name, set->version, BaseSet<Tbase_set>::SET_TYPE,
duplicate->valid_files > set->valid_files ? "less valid files" : "lower version");
set->next = BaseMedia<Tbase_set>::duplicate_sets;
BaseMedia<Tbase_set>::duplicate_sets = set;
@ -211,8 +209,7 @@ bool BaseMedia<Tbase_set>::AddFile(const std::string &filename, size_t basepath_
* version number until a new game is started which isn't a big problem */
if (BaseMedia<Tbase_set>::used_set == duplicate) BaseMedia<Tbase_set>::used_set = set;
Debug(grf, 1, "Removing {} ({}) as base {} set (duplicate, {})", duplicate->name, duplicate->version,
BaseSet<Tbase_set>::SET_TYPE,
Debug(grf, 1, "Removing {} ({}) as base {} set (duplicate, {})", duplicate->name, duplicate->version, BaseSet<Tbase_set>::SET_TYPE,
duplicate->valid_files < set->valid_files ? "less valid files" : "lower version");
duplicate->next = BaseMedia<Tbase_set>::duplicate_sets;
BaseMedia<Tbase_set>::duplicate_sets = duplicate;
@ -319,7 +316,8 @@ template <class Tbase_set>
#include "network/core/tcp_content_type.h"
template <class Tbase_set> const char *TryGetBaseSetFile(const ContentInfo &ci, bool md5sum, const Tbase_set *s)
template <class Tbase_set>
const char *TryGetBaseSetFile(const ContentInfo &ci, bool md5sum, const Tbase_set *s)
{
for (; s != nullptr; s = s->next) {
if (s->GetNumMissing() != 0) continue;
@ -339,8 +337,7 @@ template <class Tbase_set> const char *TryGetBaseSetFile(const ContentInfo &ci,
template <class Tbase_set>
/* static */ bool BaseMedia<Tbase_set>::HasSet(const ContentInfo &ci, bool md5sum)
{
return (TryGetBaseSetFile(ci, md5sum, BaseMedia<Tbase_set>::available_sets) != nullptr) ||
(TryGetBaseSetFile(ci, md5sum, BaseMedia<Tbase_set>::duplicate_sets) != nullptr);
return (TryGetBaseSetFile(ci, md5sum, BaseMedia<Tbase_set>::available_sets) != nullptr) || (TryGetBaseSetFile(ci, md5sum, BaseMedia<Tbase_set>::duplicate_sets) != nullptr);
}
/**

View File

@ -31,7 +31,8 @@ enum BlitterType : uint8_t {
struct GRFConfig;
template <> struct BaseSetTraits<struct GraphicsSet> {
template <>
struct BaseSetTraits<struct GraphicsSet> {
static constexpr size_t num_files = MAX_GFT;
static constexpr bool search_in_tars = true;
static constexpr std::string_view set_type = "graphics";
@ -49,7 +50,12 @@ public:
~GraphicsSet();
bool FillSetDetails(const IniFile &ini, const std::string &path, const std::string &full_filename);
GRFConfig *GetExtraConfig() const { return this->extra_cfg.get(); }
GRFConfig *GetExtraConfig() const
{
return this->extra_cfg.get();
}
GRFConfig &GetOrCreateExtraConfig() const;
bool IsConfigurable() const;
void CopyCompatibleConfig(const GraphicsSet &src);
@ -67,6 +73,7 @@ public:
uint32_t extra_version; ///< version of the extra GRF
std::vector<uint32_t> extra_params; ///< parameters for the extra GRF
};
static inline Ini ini_data;
};

View File

@ -43,7 +43,8 @@ struct MusicSongInfo {
int override_end; ///< MIDI tick to end the song at (0 if no override)
};
template <> struct BaseSetTraits<struct MusicSet> {
template <>
struct BaseSetTraits<struct MusicSet> {
static constexpr size_t num_files = NUM_SONGS_AVAILABLE;
static constexpr bool search_in_tars = false;
static constexpr std::string_view set_type = "music";

View File

@ -12,7 +12,8 @@
#include "base_media_base.h"
template <> struct BaseSetTraits<struct SoundsSet> {
template <>
struct BaseSetTraits<struct SoundsSet> {
static constexpr size_t num_files = 1;
static constexpr bool search_in_tars = true;
static constexpr std::string_view set_type = "sounds";

View File

@ -12,9 +12,9 @@
#include "core/pool_type.hpp"
#include "command_type.h"
#include "viewport_type.h"
#include "station_map.h"
#include "timer/timer_game_calendar.h"
#include "viewport_type.h"
typedef Pool<BaseStation, StationID, 32> StationPool;
extern StationPool _station_pool;
@ -135,7 +135,6 @@ struct BaseStation : StationPool::PoolItem<&_station_pool> {
*/
virtual void GetTileArea(TileArea *ta, StationType type) const = 0;
/**
* Obtain the length of a platform
* @pre tile must be a rail station tile
@ -194,8 +193,16 @@ private:
bool SetRoadStopTileData(TileIndex tile, uint8_t data, bool animation);
public:
inline void SetRoadStopRandomBits(TileIndex tile, uint8_t random_bits) { this->SetRoadStopTileData(tile, random_bits, false); }
inline bool SetRoadStopAnimationFrame(TileIndex tile, uint8_t frame) { return this->SetRoadStopTileData(tile, frame, true); }
inline void SetRoadStopRandomBits(TileIndex tile, uint8_t random_bits)
{
this->SetRoadStopTileData(tile, random_bits, false);
}
inline bool SetRoadStopAnimationFrame(TileIndex tile, uint8_t frame)
{
return this->SetRoadStopTileData(tile, frame, true);
}
void RemoveRoadStopTileData(TileIndex tile);
static void PostDestructor(size_t index);
@ -216,8 +223,7 @@ struct SpecializedStation : public BaseStation {
* Set station type correctly
* @param tile The base tile of the station.
*/
inline SpecializedStation(TileIndex tile) :
BaseStation(tile)
inline SpecializedStation(TileIndex tile) : BaseStation(tile)
{
this->facilities = EXPECTED_FACIL;
}
@ -297,7 +303,10 @@ struct SpecializedStation : public BaseStation {
* @param from index of the first station to consider
* @return an iterable ensemble of all valid stations of type T
*/
static Pool::IterateWrapper<T> Iterate(size_t from = 0) { return Pool::IterateWrapper<T>(from); }
static Pool::IterateWrapper<T> Iterate(size_t from = 0)
{
return Pool::IterateWrapper<T>(from);
}
};
/**
@ -306,8 +315,19 @@ struct SpecializedStation : public BaseStation {
* @param bst Station of custom spec list.
* @return Speclist of custom spec type.
*/
template <class T> std::vector<SpecMapping<T>> &GetStationSpecList(BaseStation *bst);
template <> inline std::vector<SpecMapping<StationSpec>> &GetStationSpecList<StationSpec>(BaseStation *bst) { return bst->speclist; }
template <> inline std::vector<SpecMapping<RoadStopSpec>> &GetStationSpecList<RoadStopSpec>(BaseStation *bst) { return bst->roadstop_speclist; }
template <class T>
std::vector<SpecMapping<T>> &GetStationSpecList(BaseStation *bst);
template <>
inline std::vector<SpecMapping<StationSpec>> &GetStationSpecList<StationSpec>(BaseStation *bst)
{
return bst->speclist;
}
template <>
inline std::vector<SpecMapping<RoadStopSpec>> &GetStationSpecList<RoadStopSpec>(BaseStation *bst)
{
return bst->roadstop_speclist;
}
#endif /* BASE_STATION_BASE_H */

View File

@ -10,7 +10,6 @@
#ifndef BITMAP_TYPE_HPP
#define BITMAP_TYPE_HPP
/** Represents a tile area containing containing individually set tiles.
* Each tile must be contained within the preallocated area.
* A std::vector<bool> is used to mark which tiles are contained.
@ -19,9 +18,15 @@ class BitmapTileArea : public TileArea {
protected:
std::vector<bool> data;
inline uint Index(uint x, uint y) const { return y * this->w + x; }
inline uint Index(uint x, uint y) const
{
return y * this->w + x;
}
inline uint Index(TileIndex tile) const { return Index(TileX(tile) - TileX(this->tile), TileY(tile) - TileY(this->tile)); }
inline uint Index(TileIndex tile) const
{
return Index(TileX(tile) - TileX(this->tile), TileY(tile) - TileY(this->tile));
}
public:
BitmapTileArea()
@ -106,6 +111,7 @@ public:
class BitmapTileIterator : public OrthogonalTileIterator {
protected:
const BitmapTileArea *bitmap;
public:
/**
* Construct the iterator.

View File

@ -8,9 +8,11 @@
/** @file 32bpp_anim.cpp Implementation of the optimized 32 bpp blitter with animation support. */
#include "../stdafx.h"
#include "../video/video_driver.hpp"
#include "../palette_func.h"
#include "32bpp_anim.hpp"
#include "../palette_func.h"
#include "../video/video_driver.hpp"
#include "common.hpp"
#include "../table/sprites.h"
@ -175,7 +177,6 @@ inline void Blitter_32bppAnim::Draw(const Blitter::BlitterParams *bp, ZoomLevel
}
break;
case BlitterMode::BlackRemap:
do {
*dst++ = Colour(0, 0, 0);
@ -270,13 +271,26 @@ void Blitter_32bppAnim::Draw(Blitter::BlitterParams *bp, BlitterMode mode, ZoomL
}
switch (mode) {
default: NOT_REACHED();
case BlitterMode::Normal: Draw<BlitterMode::Normal>(bp, zoom); return;
case BlitterMode::ColourRemap: Draw<BlitterMode::ColourRemap>(bp, zoom); return;
case BlitterMode::Transparent: Draw<BlitterMode::Transparent>(bp, zoom); return;
case BlitterMode::TransparentRemap: Draw<BlitterMode::TransparentRemap>(bp, zoom); return;
case BlitterMode::CrashRemap: Draw<BlitterMode::CrashRemap>(bp, zoom); return;
case BlitterMode::BlackRemap: Draw<BlitterMode::BlackRemap>(bp, zoom); return;
default:
NOT_REACHED();
case BlitterMode::Normal:
Draw<BlitterMode::Normal>(bp, zoom);
return;
case BlitterMode::ColourRemap:
Draw<BlitterMode::ColourRemap>(bp, zoom);
return;
case BlitterMode::Transparent:
Draw<BlitterMode::Transparent>(bp, zoom);
return;
case BlitterMode::TransparentRemap:
Draw<BlitterMode::TransparentRemap>(bp, zoom);
return;
case BlitterMode::CrashRemap:
Draw<BlitterMode::CrashRemap>(bp, zoom);
return;
case BlitterMode::BlackRemap:
Draw<BlitterMode::BlackRemap>(bp, zoom);
return;
}
}
@ -537,8 +551,7 @@ Blitter::PaletteAnimation Blitter_32bppAnim::UsePaletteAnimation()
void Blitter_32bppAnim::PostResize()
{
if (_screen.width != this->anim_buf_width || _screen.height != this->anim_buf_height ||
_screen.pitch != this->anim_buf_pitch) {
if (_screen.width != this->anim_buf_width || _screen.height != this->anim_buf_height || _screen.pitch != this->anim_buf_pitch) {
/* The size of the screen changed; we can assume we can wipe all data from our buffer */
this->anim_buf_width = _screen.width;
this->anim_buf_height = _screen.height;

View File

@ -23,11 +23,7 @@ protected:
Palette palette; ///< The current palette.
public:
Blitter_32bppAnim() :
anim_buf(nullptr),
anim_buf_width(0),
anim_buf_height(0),
anim_buf_pitch(0)
Blitter_32bppAnim() : anim_buf(nullptr), anim_buf_width(0), anim_buf_height(0), anim_buf_pitch(0)
{
this->palette = _cur_palette;
}
@ -44,7 +40,11 @@ public:
void PaletteAnimate(const Palette &palette) override;
Blitter::PaletteAnimation UsePaletteAnimation() override;
std::string_view GetName() override { return "32bpp-anim"; }
std::string_view GetName() override
{
return "32bpp-anim";
}
void PostResize() override;
/**
@ -64,14 +64,19 @@ public:
return across + (lines * this->anim_buf_pitch);
}
template <BlitterMode mode> void Draw(const Blitter::BlitterParams *bp, ZoomLevel zoom);
template <BlitterMode mode>
void Draw(const Blitter::BlitterParams *bp, ZoomLevel zoom);
};
/** Factory for the 32bpp blitter with animation. */
class FBlitter_32bppAnim : public BlitterFactory {
public:
FBlitter_32bppAnim() : BlitterFactory("32bpp-anim", "32bpp Animation Blitter (palette animation)") {}
std::unique_ptr<Blitter> CreateInstance() override { return std::make_unique<Blitter_32bppAnim>(); }
std::unique_ptr<Blitter> CreateInstance() override
{
return std::make_unique<Blitter_32bppAnim>();
}
};
#endif /* BLITTER_32BPP_ANIM_HPP */

View File

@ -10,8 +10,10 @@
#ifdef WITH_SSE
# include "../stdafx.h"
#include "../video/video_driver.hpp"
# include "32bpp_anim_sse2.hpp"
# include "../video/video_driver.hpp"
# include "32bpp_sse_func.hpp"
# include "../safeguards.h"
@ -20,6 +22,7 @@
static FBlitter_32bppSSE2_Anim iFBlitter_32bppSSE2_Anim;
GNU_TARGET("sse2")
void Blitter_32bppSSE2_Anim::PaletteAnimate(const Palette &palette)
{
assert(!_screen_disable_anim);
@ -56,8 +59,7 @@ void Blitter_32bppSSE2_Anim::PaletteAnimate(const Palette &palette)
int colour_cmp_result = _mm_movemask_epi8(_mm_cmpgt_epi16(colour_data, anim_cmp));
if (colour_cmp_result) {
/* test if any brightness is unexpected */
if (x < 8 || colour_cmp_result != 0xFFFF ||
_mm_movemask_epi8(_mm_cmpeq_epi16(_mm_srli_epi16(data, 8), brightness_cmp)) != 0xFFFF) {
if (x < 8 || colour_cmp_result != 0xFFFF || _mm_movemask_epi8(_mm_cmpeq_epi16(_mm_srli_epi16(data, 8), brightness_cmp)) != 0xFFFF) {
/* slow path: < 8 pixels left or unexpected brightnesses */
for (int z = std::min<int>(x, 8); z != 0; z--) {
int value = _mm_extract_epi16(data, 0);

View File

@ -31,14 +31,22 @@
class Blitter_32bppSSE2_Anim : public Blitter_32bppAnim {
public:
void PaletteAnimate(const Palette &palette) override;
std::string_view GetName() override { return "32bpp-sse2-anim"; }
std::string_view GetName() override
{
return "32bpp-sse2-anim";
}
};
/** Factory for the partially 32bpp blitter with animation. */
class FBlitter_32bppSSE2_Anim : public BlitterFactory {
public:
FBlitter_32bppSSE2_Anim() : BlitterFactory("32bpp-sse2-anim", "32bpp partially SSE2 Animation Blitter (palette animation)", HasCPUIDFlag(1, 3, 26)) {}
std::unique_ptr<Blitter> CreateInstance() override { return std::make_unique<Blitter_32bppSSE2_Anim>(); }
std::unique_ptr<Blitter> CreateInstance() override
{
return std::make_unique<Blitter_32bppSSE2_Anim>();
}
};
#endif /* WITH_SSE */

View File

@ -10,12 +10,15 @@
#ifdef WITH_SSE
# include "../stdafx.h"
# include "32bpp_anim_sse4.hpp"
# include "../palette_func.h"
# include "../video/video_driver.hpp"
#include "../table/sprites.h"
#include "32bpp_anim_sse4.hpp"
# include "32bpp_sse_func.hpp"
# include "../table/sprites.h"
# include "../safeguards.h"
/** Instantiation of the SSE4 32bpp blitter factory. */
@ -332,7 +335,6 @@ bmcr_alpha_blend_single:
}
break;
case BlitterMode::CrashRemap:
for (uint x = (uint)bp->width; x > 0; x--) {
if (src_mv->m == 0) {
@ -373,6 +375,7 @@ next_line:
anim_line += this->anim_buf_pitch;
}
}
IGNORE_UNINITIALIZED_WARNING_STOP
/**
@ -397,24 +400,34 @@ bm_normal:
if (bp->skip_left != 0 || bp->width <= MARGIN_NORMAL_THRESHOLD) {
const BlockType bt_last = (BlockType)(bp->width & 1);
if (bt_last == BT_EVEN) {
if (sprite_flags.Test(SpriteFlag::NoAnim)) Draw<BlitterMode::Normal, RM_WITH_SKIP, BT_EVEN, true, false>(bp, zoom);
else Draw<BlitterMode::Normal, RM_WITH_SKIP, BT_EVEN, true, true>(bp, zoom);
if (sprite_flags.Test(SpriteFlag::NoAnim))
Draw<BlitterMode::Normal, RM_WITH_SKIP, BT_EVEN, true, false>(bp, zoom);
else
Draw<BlitterMode::Normal, RM_WITH_SKIP, BT_EVEN, true, true>(bp, zoom);
} else {
if (sprite_flags.Test(SpriteFlag::NoAnim)) Draw<BlitterMode::Normal, RM_WITH_SKIP, BT_ODD, true, false>(bp, zoom);
else Draw<BlitterMode::Normal, RM_WITH_SKIP, BT_ODD, true, true>(bp, zoom);
if (sprite_flags.Test(SpriteFlag::NoAnim))
Draw<BlitterMode::Normal, RM_WITH_SKIP, BT_ODD, true, false>(bp, zoom);
else
Draw<BlitterMode::Normal, RM_WITH_SKIP, BT_ODD, true, true>(bp, zoom);
}
} else {
# ifdef POINTER_IS_64BIT
if (sprite_flags.Test(SpriteFlag::Translucent)) {
if (sprite_flags.Test(SpriteFlag::NoAnim)) Draw<BlitterMode::Normal, RM_WITH_MARGIN, BT_NONE, true, false>(bp, zoom);
else Draw<BlitterMode::Normal, RM_WITH_MARGIN, BT_NONE, true, true>(bp, zoom);
if (sprite_flags.Test(SpriteFlag::NoAnim))
Draw<BlitterMode::Normal, RM_WITH_MARGIN, BT_NONE, true, false>(bp, zoom);
else
Draw<BlitterMode::Normal, RM_WITH_MARGIN, BT_NONE, true, true>(bp, zoom);
} else {
if (sprite_flags.Test(SpriteFlag::NoAnim)) Draw<BlitterMode::Normal, RM_WITH_MARGIN, BT_NONE, false, false>(bp, zoom);
else Draw<BlitterMode::Normal, RM_WITH_MARGIN, BT_NONE, false, true>(bp, zoom);
if (sprite_flags.Test(SpriteFlag::NoAnim))
Draw<BlitterMode::Normal, RM_WITH_MARGIN, BT_NONE, false, false>(bp, zoom);
else
Draw<BlitterMode::Normal, RM_WITH_MARGIN, BT_NONE, false, true>(bp, zoom);
}
# else
if (sprite_flags.Test(SpriteFlag::NoAnim)) Draw<BlitterMode::Normal, RM_WITH_MARGIN, BT_NONE, true, false>(bp, zoom);
else Draw<BlitterMode::Normal, RM_WITH_MARGIN, BT_NONE, true, true>(bp, zoom);
if (sprite_flags.Test(SpriteFlag::NoAnim))
Draw<BlitterMode::Normal, RM_WITH_MARGIN, BT_NONE, true, false>(bp, zoom);
else
Draw<BlitterMode::Normal, RM_WITH_MARGIN, BT_NONE, true, true>(bp, zoom);
# endif
}
break;
@ -422,17 +435,29 @@ bm_normal:
case BlitterMode::ColourRemap:
if (sprite_flags.Test(SpriteFlag::NoRemap)) goto bm_normal;
if (bp->skip_left != 0 || bp->width <= MARGIN_REMAP_THRESHOLD) {
if (sprite_flags.Test(SpriteFlag::NoAnim)) Draw<BlitterMode::ColourRemap, RM_WITH_SKIP, BT_NONE, true, false>(bp, zoom);
else Draw<BlitterMode::ColourRemap, RM_WITH_SKIP, BT_NONE, true, true>(bp, zoom);
if (sprite_flags.Test(SpriteFlag::NoAnim))
Draw<BlitterMode::ColourRemap, RM_WITH_SKIP, BT_NONE, true, false>(bp, zoom);
else
Draw<BlitterMode::ColourRemap, RM_WITH_SKIP, BT_NONE, true, true>(bp, zoom);
} else {
if (sprite_flags.Test(SpriteFlag::NoAnim)) Draw<BlitterMode::ColourRemap, RM_WITH_MARGIN, BT_NONE, true, false>(bp, zoom);
else Draw<BlitterMode::ColourRemap, RM_WITH_MARGIN, BT_NONE, true, true>(bp, zoom);
if (sprite_flags.Test(SpriteFlag::NoAnim))
Draw<BlitterMode::ColourRemap, RM_WITH_MARGIN, BT_NONE, true, false>(bp, zoom);
else
Draw<BlitterMode::ColourRemap, RM_WITH_MARGIN, BT_NONE, true, true>(bp, zoom);
}
break;
case BlitterMode::Transparent: Draw<BlitterMode::Transparent, RM_NONE, BT_NONE, true, true>(bp, zoom); return;
case BlitterMode::TransparentRemap: Draw<BlitterMode::TransparentRemap, RM_NONE, BT_NONE, true, true>(bp, zoom); return;
case BlitterMode::CrashRemap: Draw<BlitterMode::CrashRemap, RM_NONE, BT_NONE, true, true>(bp, zoom); return;
case BlitterMode::BlackRemap: Draw<BlitterMode::BlackRemap, RM_NONE, BT_NONE, true, true>(bp, zoom); return;
case BlitterMode::Transparent:
Draw<BlitterMode::Transparent, RM_NONE, BT_NONE, true, true>(bp, zoom);
return;
case BlitterMode::TransparentRemap:
Draw<BlitterMode::TransparentRemap, RM_NONE, BT_NONE, true, true>(bp, zoom);
return;
case BlitterMode::CrashRemap:
Draw<BlitterMode::CrashRemap, RM_NONE, BT_NONE, true, true>(bp, zoom);
return;
case BlitterMode::BlackRemap:
Draw<BlitterMode::BlackRemap, RM_NONE, BT_NONE, true, true>(bp, zoom);
return;
}
}

View File

@ -34,15 +34,21 @@
/** The SSE4 32 bpp blitter with palette animation. */
class Blitter_32bppSSE4_Anim final : public Blitter_32bppSSE2_Anim, public Blitter_32bppSSE4 {
private:
public:
template <BlitterMode mode, Blitter_32bppSSE_Base::ReadMode read_mode, Blitter_32bppSSE_Base::BlockType bt_last, bool translucent, bool animated>
void Draw(const Blitter::BlitterParams *bp, ZoomLevel zoom);
void Draw(Blitter::BlitterParams *bp, BlitterMode mode, ZoomLevel zoom) override;
Sprite *Encode(const SpriteLoader::SpriteCollection &sprite, SpriteAllocator &allocator) override {
Sprite *Encode(const SpriteLoader::SpriteCollection &sprite, SpriteAllocator &allocator) override
{
return Blitter_32bppSSE_Base::Encode(sprite, allocator);
}
std::string_view GetName() override { return "32bpp-sse4-anim"; }
std::string_view GetName() override
{
return "32bpp-sse4-anim";
}
using Blitter_32bppSSE2_Anim::LookupColourInPalette;
};
@ -50,7 +56,11 @@ public:
class FBlitter_32bppSSE4_Anim : public BlitterFactory {
public:
FBlitter_32bppSSE4_Anim() : BlitterFactory("32bpp-sse4-anim", "32bpp SSE4 Blitter (palette animation)", HasCPUIDFlag(1, 2, 19)) {}
std::unique_ptr<Blitter> CreateInstance() override { return std::unique_ptr<Blitter>(static_cast<Blitter_32bppSSE2_Anim *>(new Blitter_32bppSSE4_Anim())); }
std::unique_ptr<Blitter> CreateInstance() override
{
return std::unique_ptr<Blitter>(static_cast<Blitter_32bppSSE2_Anim *>(new Blitter_32bppSSE4_Anim()));
}
};
#endif /* WITH_SSE */

View File

@ -8,7 +8,9 @@
/** @file 32bpp_base.cpp Implementation of base for 32 bpp blitters. */
#include "../stdafx.h"
#include "32bpp_base.hpp"
#include "common.hpp"
#include "../safeguards.h"

View File

@ -10,14 +10,18 @@
#ifndef BLITTER_32BPP_BASE_HPP
#define BLITTER_32BPP_BASE_HPP
#include "base.hpp"
#include "../gfx_func.h"
#include "../palette_func.h"
#include "base.hpp"
/** Base for all 32bpp blitters. */
class Blitter_32bppBase : public Blitter {
public:
uint8_t GetScreenDepth() override { return 32; }
uint8_t GetScreenDepth() override
{
return 32;
}
void *MoveTo(void *video, int x, int y) override;
void SetPixel(void *video, int x, int y, uint8_t colour) override;
void DrawLine(void *video, int x, int y, int x2, int y2, int screen_width, int screen_height, uint8_t colour, int width, int dash) override;
@ -48,10 +52,7 @@ public:
uint cb = current.b;
/* The 256 is wrong, it should be 255, but 256 is much faster... */
return Colour(
((int)(r - cr) * a) / 256 + cr,
((int)(g - cg) * a) / 256 + cg,
((int)(b - cb) * a) / 256 + cb);
return Colour(((int)(r - cr) * a) / 256 + cr, ((int)(g - cg) * a) / 256 + cg, ((int)(b - cb) * a) / 256 + cb);
}
/**

View File

@ -8,11 +8,13 @@
/** @file 32bpp_optimized.cpp Implementation of the optimized 32 bpp blitter. */
#include "../stdafx.h"
#include "../zoom_func.h"
#include "../settings_type.h"
#include "../palette_func.h"
#include "32bpp_optimized.hpp"
#include "../palette_func.h"
#include "../settings_type.h"
#include "../zoom_func.h"
#include "../safeguards.h"
/** Instantiation of the optimized 32bpp blitter factory. */
@ -260,13 +262,26 @@ template <bool Tpal_to_rgb>
void Blitter_32bppOptimized::Draw(Blitter::BlitterParams *bp, BlitterMode mode, ZoomLevel zoom)
{
switch (mode) {
default: NOT_REACHED();
case BlitterMode::Normal: Draw<BlitterMode::Normal, Tpal_to_rgb>(bp, zoom); return;
case BlitterMode::ColourRemap: Draw<BlitterMode::ColourRemap, Tpal_to_rgb>(bp, zoom); return;
case BlitterMode::Transparent: Draw<BlitterMode::Transparent, Tpal_to_rgb>(bp, zoom); return;
case BlitterMode::TransparentRemap: Draw<BlitterMode::TransparentRemap, Tpal_to_rgb>(bp, zoom); return;
case BlitterMode::CrashRemap: Draw<BlitterMode::CrashRemap, Tpal_to_rgb>(bp, zoom); return;
case BlitterMode::BlackRemap: Draw<BlitterMode::BlackRemap, Tpal_to_rgb>(bp, zoom); return;
default:
NOT_REACHED();
case BlitterMode::Normal:
Draw<BlitterMode::Normal, Tpal_to_rgb>(bp, zoom);
return;
case BlitterMode::ColourRemap:
Draw<BlitterMode::ColourRemap, Tpal_to_rgb>(bp, zoom);
return;
case BlitterMode::Transparent:
Draw<BlitterMode::Transparent, Tpal_to_rgb>(bp, zoom);
return;
case BlitterMode::TransparentRemap:
Draw<BlitterMode::TransparentRemap, Tpal_to_rgb>(bp, zoom);
return;
case BlitterMode::CrashRemap:
Draw<BlitterMode::CrashRemap, Tpal_to_rgb>(bp, zoom);
return;
case BlitterMode::BlackRemap:
Draw<BlitterMode::BlackRemap, Tpal_to_rgb>(bp, zoom);
return;
}
}
@ -285,7 +300,8 @@ void Blitter_32bppOptimized::Draw(Blitter::BlitterParams *bp, BlitterMode mode,
this->Draw<false>(bp, mode, zoom);
}
template <bool Tpal_to_rgb> Sprite *Blitter_32bppOptimized::EncodeInternal(const SpriteLoader::SpriteCollection &sprite, SpriteAllocator &allocator)
template <bool Tpal_to_rgb>
Sprite *Blitter_32bppOptimized::EncodeInternal(const SpriteLoader::SpriteCollection &sprite, SpriteAllocator &allocator)
{
/* streams of pixels (a, r, g, b channels)
*

View File

@ -24,20 +24,30 @@ public:
void Draw(Blitter::BlitterParams *bp, BlitterMode mode, ZoomLevel zoom) override;
Sprite *Encode(const SpriteLoader::SpriteCollection &sprite, SpriteAllocator &allocator) override;
std::string_view GetName() override { return "32bpp-optimized"; }
std::string_view GetName() override
{
return "32bpp-optimized";
}
template <BlitterMode mode, bool Tpal_to_rgb = false> void Draw(const Blitter::BlitterParams *bp, ZoomLevel zoom);
template <BlitterMode mode, bool Tpal_to_rgb = false>
void Draw(const Blitter::BlitterParams *bp, ZoomLevel zoom);
protected:
template <bool Tpal_to_rgb> void Draw(Blitter::BlitterParams *bp, BlitterMode mode, ZoomLevel zoom);
template <bool Tpal_to_rgb> Sprite *EncodeInternal(const SpriteLoader::SpriteCollection &sprite, SpriteAllocator &allocator);
template <bool Tpal_to_rgb>
void Draw(Blitter::BlitterParams *bp, BlitterMode mode, ZoomLevel zoom);
template <bool Tpal_to_rgb>
Sprite *EncodeInternal(const SpriteLoader::SpriteCollection &sprite, SpriteAllocator &allocator);
};
/** Factory for the optimised 32 bpp blitter (without palette animation). */
class FBlitter_32bppOptimized : public BlitterFactory {
public:
FBlitter_32bppOptimized() : BlitterFactory("32bpp-optimized", "32bpp Optimized Blitter (no palette animation)") {}
std::unique_ptr<Blitter> CreateInstance() override { return std::make_unique<Blitter_32bppOptimized>(); }
std::unique_ptr<Blitter> CreateInstance() override
{
return std::make_unique<Blitter_32bppOptimized>();
}
};
#endif /* BLITTER_32BPP_OPTIMIZED_HPP */

View File

@ -8,10 +8,12 @@
/** @file 32bpp_simple.cpp Implementation of the simple 32 bpp blitter. */
#include "../stdafx.h"
#include "../zoom_func.h"
#include "../palette_func.h"
#include "32bpp_simple.hpp"
#include "../palette_func.h"
#include "../zoom_func.h"
#include "../table/sprites.h"
#include "../safeguards.h"

View File

@ -23,19 +23,27 @@ class Blitter_32bppSimple : public Blitter_32bppBase {
uint8_t m; ///< Remap-channel
uint8_t v; ///< Brightness-channel
};
public:
void Draw(Blitter::BlitterParams *bp, BlitterMode mode, ZoomLevel zoom) override;
void DrawColourMappingRect(void *dst, int width, int height, PaletteID pal) override;
Sprite *Encode(const SpriteLoader::SpriteCollection &sprite, SpriteAllocator &allocator) override;
std::string_view GetName() override { return "32bpp-simple"; }
std::string_view GetName() override
{
return "32bpp-simple";
}
};
/** Factory for the simple 32 bpp blitter. */
class FBlitter_32bppSimple : public BlitterFactory {
public:
FBlitter_32bppSimple() : BlitterFactory("32bpp-simple", "32bpp Simple Blitter (no palette animation)") {}
std::unique_ptr<Blitter> CreateInstance() override { return std::make_unique<Blitter_32bppSimple>(); }
std::unique_ptr<Blitter> CreateInstance() override
{
return std::make_unique<Blitter_32bppSimple>();
}
};
#endif /* BLITTER_32BPP_SIMPLE_HPP */

View File

@ -10,9 +10,11 @@
#ifdef WITH_SSE
# include "../stdafx.h"
#include "../zoom_func.h"
#include "../settings_type.h"
# include "32bpp_sse2.hpp"
# include "../settings_type.h"
# include "../zoom_func.h"
# include "32bpp_sse_func.hpp"
# include "../safeguards.h"
@ -106,8 +108,10 @@ Sprite *Blitter_32bppSSE_Base::Encode(const SpriteLoader::SpriteCollection &spri
dst_rgba = dst_rgba_line + META_LENGTH;
uint32_t nb_pix_transp = 0;
for (uint x = src_sprite->width; x != 0; x--) {
if (dst_rgba->a == 0) nb_pix_transp++;
else break;
if (dst_rgba->a == 0)
nb_pix_transp++;
else
break;
dst_rgba++;
}
(*dst_rgba_line).data = nb_pix_transp;
@ -119,8 +123,10 @@ Sprite *Blitter_32bppSSE_Base::Encode(const SpriteLoader::SpriteCollection &spri
dst_rgba = dst_rgba_line - 1;
nb_pix_transp = 0;
for (uint x = src_sprite->width; x != 0; x--) {
if (dst_rgba->a == 0) nb_pix_transp++;
else break;
if (dst_rgba->a == 0)
nb_pix_transp++;
else
break;
dst_rgba--;
}
(*nb_right).data = nb_pix_transp;

View File

@ -35,6 +35,7 @@ public:
uint8_t m;
uint8_t v;
};
static_assert(sizeof(MapValue) == 2);
/** Helper for creating specialised functions for specific optimisations. */
@ -71,6 +72,7 @@ public:
uint16_t sprite_line_size = 0; ///< The size of a single line (pitch).
uint16_t sprite_width = 0; ///< The width of the sprite.
};
struct SpriteData {
SpriteFlags flags{};
std::array<SpriteInfo, ZOOM_LVL_END> infos{};
@ -87,18 +89,26 @@ public:
template <BlitterMode mode, Blitter_32bppSSE_Base::ReadMode read_mode, Blitter_32bppSSE_Base::BlockType bt_last, bool translucent>
void Draw(const Blitter::BlitterParams *bp, ZoomLevel zoom);
Sprite *Encode(const SpriteLoader::SpriteCollection &sprite, SpriteAllocator &allocator) override {
Sprite *Encode(const SpriteLoader::SpriteCollection &sprite, SpriteAllocator &allocator) override
{
return Blitter_32bppSSE_Base::Encode(sprite, allocator);
}
std::string_view GetName() override { return "32bpp-sse2"; }
std::string_view GetName() override
{
return "32bpp-sse2";
}
};
/** Factory for the SSE2 32 bpp blitter (without palette animation). */
class FBlitter_32bppSSE2 : public BlitterFactory {
public:
FBlitter_32bppSSE2() : BlitterFactory("32bpp-sse2", "32bpp SSE2 Blitter (no palette animation)", HasCPUIDFlag(1, 3, 26)) {}
std::unique_ptr<Blitter> CreateInstance() override { return std::make_unique<Blitter_32bppSSE2>(); }
std::unique_ptr<Blitter> CreateInstance() override
{
return std::make_unique<Blitter_32bppSSE2>();
}
};
#endif /* WITH_SSE */

View File

@ -10,9 +10,11 @@
#ifdef WITH_SSE
# include "../stdafx.h"
#include "../zoom_func.h"
#include "../settings_type.h"
# include "32bpp_sse4.hpp"
# include "../settings_type.h"
# include "../zoom_func.h"
# include "32bpp_sse_func.hpp"
# include "../safeguards.h"

View File

@ -32,14 +32,22 @@ public:
void Draw(Blitter::BlitterParams *bp, BlitterMode mode, ZoomLevel zoom) override;
template <BlitterMode mode, Blitter_32bppSSE_Base::ReadMode read_mode, Blitter_32bppSSE_Base::BlockType bt_last, bool translucent>
void Draw(const Blitter::BlitterParams *bp, ZoomLevel zoom);
std::string_view GetName() override { return "32bpp-sse4"; }
std::string_view GetName() override
{
return "32bpp-sse4";
}
};
/** Factory for the SSE4 32 bpp blitter (without palette animation). */
class FBlitter_32bppSSE4 : public BlitterFactory {
public:
FBlitter_32bppSSE4() : BlitterFactory("32bpp-sse4", "32bpp SSE4 Blitter (no palette animation)", HasCPUIDFlag(1, 2, 19)) {}
std::unique_ptr<Blitter> CreateInstance() override { return std::make_unique<Blitter_32bppSSE4>(); }
std::unique_ptr<Blitter> CreateInstance() override
{
return std::make_unique<Blitter_32bppSSE4>();
}
};
#endif /* WITH_SSE */

View File

@ -20,6 +20,7 @@
#ifdef WITH_SSE
GNU_TARGET(SSE_TARGET)
INTERNAL_LINKAGE inline void InsertFirstUint32(const uint32_t value, __m128i &into)
{
# if (SSE_VERSION >= 4)
@ -31,6 +32,7 @@ INTERNAL_LINKAGE inline void InsertFirstUint32(const uint32_t value, __m128i &in
}
GNU_TARGET(SSE_TARGET)
INTERNAL_LINKAGE inline void InsertSecondUint32(const uint32_t value, __m128i &into)
{
# if (SSE_VERSION >= 4)
@ -42,6 +44,7 @@ INTERNAL_LINKAGE inline void InsertSecondUint32(const uint32_t value, __m128i &i
}
GNU_TARGET(SSE_TARGET)
INTERNAL_LINKAGE inline void LoadUint64(const uint64_t value, __m128i &into)
{
# ifdef POINTER_IS_64BIT
@ -57,6 +60,7 @@ INTERNAL_LINKAGE inline void LoadUint64(const uint64_t value, __m128i &into)
}
GNU_TARGET(SSE_TARGET)
INTERNAL_LINKAGE inline __m128i PackUnsaturated(__m128i from, const __m128i &mask)
{
# if (SSE_VERSION == 2)
@ -68,6 +72,7 @@ INTERNAL_LINKAGE inline __m128i PackUnsaturated(__m128i from, const __m128i &mas
}
GNU_TARGET(SSE_TARGET)
INTERNAL_LINKAGE inline __m128i DistributeAlpha(const __m128i from, const __m128i &mask)
{
# if (SSE_VERSION == 2)
@ -80,6 +85,7 @@ INTERNAL_LINKAGE inline __m128i DistributeAlpha(const __m128i from, const __m128
}
GNU_TARGET(SSE_TARGET)
INTERNAL_LINKAGE inline __m128i AlphaBlendTwoPixels(__m128i src, __m128i dst, const __m128i &distribution_mask, const __m128i &pack_mask, const __m128i &alpha_mask)
{
__m128i srcAB = _mm_unpacklo_epi8(src, _mm_setzero_si128()); // PUNPCKLBW, expand each uint8_t into uint16
@ -104,6 +110,7 @@ INTERNAL_LINKAGE inline __m128i AlphaBlendTwoPixels(__m128i src, __m128i dst, co
* rgb = rgb * ((256/4) * 4 - (alpha/4)) / ((256/4) * 4)
*/
GNU_TARGET(SSE_TARGET)
INTERNAL_LINKAGE inline __m128i DarkenTwoPixels(__m128i src, __m128i dst, const __m128i &distribution_mask, const __m128i &tr_nom_base)
{
__m128i srcAB = _mm_unpacklo_epi8(src, _mm_setzero_si128());
@ -118,6 +125,7 @@ INTERNAL_LINKAGE inline __m128i DarkenTwoPixels(__m128i src, __m128i dst, const
IGNORE_UNINITIALIZED_WARNING_START
GNU_TARGET(SSE_TARGET)
INTERNAL_LINKAGE Colour ReallyAdjustBrightness(Colour colour, uint8_t brightness)
{
uint64_t c16 = colour.b | (uint64_t)colour.g << 16 | (uint64_t)colour.r << 32;
@ -147,6 +155,7 @@ INTERNAL_LINKAGE Colour ReallyAdjustBrightness(Colour colour, uint8_t brightness
ret = _mm_packus_epi16(ret, ret); // PACKUSWB, saturate and pack.
return alpha32 | _mm_cvtsi128_si32(ret);
}
IGNORE_UNINITIALIZED_WARNING_STOP
/** ReallyAdjustBrightness() is not called that often.
@ -161,6 +170,7 @@ INTERNAL_LINKAGE inline Colour AdjustBrightneSSE(Colour colour, uint8_t brightne
}
GNU_TARGET(SSE_TARGET)
INTERNAL_LINKAGE inline __m128i AdjustBrightnessOfTwoPixels([[maybe_unused]] __m128i from, [[maybe_unused]] uint32_t brightness)
{
# if (SSE_VERSION < 3)
@ -469,8 +479,12 @@ void Blitter_32bppSSE4::Draw(Blitter::BlitterParams *bp, BlitterMode mode, ZoomL
bm_normal:
const BlockType bt_last = (BlockType)(bp->width & 1);
switch (bt_last) {
default: Draw<BlitterMode::Normal, RM_WITH_SKIP, BT_EVEN, true>(bp, zoom); return;
case BT_ODD: Draw<BlitterMode::Normal, RM_WITH_SKIP, BT_ODD, true>(bp, zoom); return;
default:
Draw<BlitterMode::Normal, RM_WITH_SKIP, BT_EVEN, true>(bp, zoom);
return;
case BT_ODD:
Draw<BlitterMode::Normal, RM_WITH_SKIP, BT_ODD, true>(bp, zoom);
return;
}
} else {
if (((const Blitter_32bppSSE_Base::SpriteData *)bp->sprite)->flags.Test(SpriteFlag::Translucent)) {
@ -485,14 +499,24 @@ bm_normal:
case BlitterMode::ColourRemap:
if (((const Blitter_32bppSSE_Base::SpriteData *)bp->sprite)->flags.Test(SpriteFlag::NoRemap)) goto bm_normal;
if (bp->skip_left != 0 || bp->width <= MARGIN_REMAP_THRESHOLD) {
Draw<BlitterMode::ColourRemap, RM_WITH_SKIP, BT_NONE, true>(bp, zoom); return;
Draw<BlitterMode::ColourRemap, RM_WITH_SKIP, BT_NONE, true>(bp, zoom);
return;
} else {
Draw<BlitterMode::ColourRemap, RM_WITH_MARGIN, BT_NONE, true>(bp, zoom); return;
Draw<BlitterMode::ColourRemap, RM_WITH_MARGIN, BT_NONE, true>(bp, zoom);
return;
}
case BlitterMode::Transparent: Draw<BlitterMode::Transparent, RM_NONE, BT_NONE, true>(bp, zoom); return;
case BlitterMode::TransparentRemap: Draw<BlitterMode::TransparentRemap, RM_NONE, BT_NONE, true>(bp, zoom); return;
case BlitterMode::CrashRemap: Draw<BlitterMode::CrashRemap, RM_NONE, BT_NONE, true>(bp, zoom); return;
case BlitterMode::BlackRemap: Draw<BlitterMode::BlackRemap, RM_NONE, BT_NONE, true>(bp, zoom); return;
case BlitterMode::Transparent:
Draw<BlitterMode::Transparent, RM_NONE, BT_NONE, true>(bp, zoom);
return;
case BlitterMode::TransparentRemap:
Draw<BlitterMode::TransparentRemap, RM_NONE, BT_NONE, true>(bp, zoom);
return;
case BlitterMode::CrashRemap:
Draw<BlitterMode::CrashRemap, RM_NONE, BT_NONE, true>(bp, zoom);
return;
case BlitterMode::BlackRemap:
Draw<BlitterMode::BlackRemap, RM_NONE, BT_NONE, true>(bp, zoom);
return;
}
}
# endif /* FULL_ANIMATION */

View File

@ -10,9 +10,11 @@
#ifdef WITH_SSE
# include "../stdafx.h"
#include "../zoom_func.h"
#include "../settings_type.h"
# include "32bpp_ssse3.hpp"
# include "../settings_type.h"
# include "../zoom_func.h"
# include "32bpp_sse_func.hpp"
# include "../safeguards.h"

View File

@ -32,14 +32,22 @@ public:
void Draw(Blitter::BlitterParams *bp, BlitterMode mode, ZoomLevel zoom) override;
template <BlitterMode mode, Blitter_32bppSSE_Base::ReadMode read_mode, Blitter_32bppSSE_Base::BlockType bt_last, bool translucent>
void Draw(const Blitter::BlitterParams *bp, ZoomLevel zoom);
std::string_view GetName() override { return "32bpp-ssse3"; }
std::string_view GetName() override
{
return "32bpp-ssse3";
}
};
/** Factory for the SSSE3 32 bpp blitter (without palette animation). */
class FBlitter_32bppSSSE3 : public BlitterFactory {
public:
FBlitter_32bppSSSE3() : BlitterFactory("32bpp-ssse3", "32bpp SSSE3 Blitter (no palette animation)", HasCPUIDFlag(1, 2, 9)) {}
std::unique_ptr<Blitter> CreateInstance() override { return std::make_unique<Blitter_32bppSSSE3>(); }
std::unique_ptr<Blitter> CreateInstance() override
{
return std::make_unique<Blitter_32bppSSSE3>();
}
};
#endif /* WITH_SSE */

View File

@ -8,25 +8,25 @@
/** @file 40bpp_optimized.cpp Implementation of the optimized 40 bpp blitter. */
#include "../stdafx.h"
#include "../zoom_func.h"
#include "40bpp_anim.hpp"
#include "../palette_func.h"
#include "../settings_type.h"
#include "../video/video_driver.hpp"
#include "../palette_func.h"
#include "40bpp_anim.hpp"
#include "../zoom_func.h"
#include "common.hpp"
#include "../table/sprites.h"
#include "../safeguards.h"
/** Instantiation of the 40bpp with animation blitter factory. */
static FBlitter_40bppAnim iFBlitter_40bppAnim;
/** Cached black value. */
static const Colour _black_colour(0, 0, 0);
void Blitter_40bppAnim::SetPixel(void *video, int x, int y, uint8_t colour)
{
if (_screen_disable_anim) {
@ -338,13 +338,26 @@ void Blitter_40bppAnim::Draw(Blitter::BlitterParams *bp, BlitterMode mode, ZoomL
}
switch (mode) {
default: NOT_REACHED();
case BlitterMode::Normal: Draw<BlitterMode::Normal>(bp, zoom); return;
case BlitterMode::ColourRemap: Draw<BlitterMode::ColourRemap>(bp, zoom); return;
case BlitterMode::Transparent: Draw<BlitterMode::Transparent>(bp, zoom); return;
case BlitterMode::TransparentRemap: Draw<BlitterMode::TransparentRemap>(bp, zoom); return;
case BlitterMode::CrashRemap: Draw<BlitterMode::CrashRemap>(bp, zoom); return;
case BlitterMode::BlackRemap: Draw<BlitterMode::BlackRemap>(bp, zoom); return;
default:
NOT_REACHED();
case BlitterMode::Normal:
Draw<BlitterMode::Normal>(bp, zoom);
return;
case BlitterMode::ColourRemap:
Draw<BlitterMode::ColourRemap>(bp, zoom);
return;
case BlitterMode::Transparent:
Draw<BlitterMode::Transparent>(bp, zoom);
return;
case BlitterMode::TransparentRemap:
Draw<BlitterMode::TransparentRemap>(bp, zoom);
return;
case BlitterMode::CrashRemap:
Draw<BlitterMode::CrashRemap>(bp, zoom);
return;
case BlitterMode::BlackRemap:
Draw<BlitterMode::BlackRemap>(bp, zoom);
return;
}
}
@ -402,7 +415,6 @@ Sprite *Blitter_40bppAnim::Encode(const SpriteLoader::SpriteCollection &sprite,
return this->EncodeInternal<false>(sprite, allocator);
}
void Blitter_40bppAnim::CopyFromBuffer(void *video, const void *src, int width, int height)
{
assert(!_screen_disable_anim);

View File

@ -10,14 +10,12 @@
#ifndef BLITTER_40BPP_OPTIMIZED_HPP
#define BLITTER_40BPP_OPTIMIZED_HPP
#include "32bpp_optimized.hpp"
#include "../video/video_driver.hpp"
#include "32bpp_optimized.hpp"
/** The optimized 40 bpp blitter (for OpenGL video driver). */
class Blitter_40bppAnim : public Blitter_32bppOptimized {
public:
void SetPixel(void *video, int x, int y, uint8_t colour) override;
void DrawRect(void *video, int width, int height, uint8_t colour) override;
void DrawLine(void *video, int x, int y, int x2, int y2, int screen_width, int screen_height, uint8_t colour, int width, int dash) override;
@ -32,16 +30,19 @@ public:
Blitter::PaletteAnimation UsePaletteAnimation() override;
bool NeedsAnimationBuffer() override;
std::string_view GetName() override { return "40bpp-anim"; }
std::string_view GetName() override
{
return "40bpp-anim";
}
template <BlitterMode mode> void Draw(const Blitter::BlitterParams *bp, ZoomLevel zoom);
template <BlitterMode mode>
void Draw(const Blitter::BlitterParams *bp, ZoomLevel zoom);
protected:
static inline Colour RealizeBlendedColour(uint8_t anim, Colour c)
{
return anim != 0 ? AdjustBrightness(LookupColourInPalette(anim), GetColourBrightness(c)) : c;
}
};
/** Factory for the 40 bpp animated blitter (for OpenGL). */
@ -54,7 +55,11 @@ protected:
public:
FBlitter_40bppAnim() : BlitterFactory("40bpp-anim", "40bpp Animation Blitter (OpenGL)") {}
std::unique_ptr<Blitter> CreateInstance() override { return std::make_unique<Blitter_40bppAnim>(); }
std::unique_ptr<Blitter> CreateInstance() override
{
return std::make_unique<Blitter_40bppAnim>();
}
};
#endif /* BLITTER_40BPP_OPTIMIZED_HPP */

View File

@ -8,8 +8,10 @@
/** @file 8bpp_base.cpp Implementation of the base for all 8 bpp blitters. */
#include "../stdafx.h"
#include "../gfx_func.h"
#include "8bpp_base.hpp"
#include "../gfx_func.h"
#include "common.hpp"
#include "../safeguards.h"

View File

@ -15,7 +15,11 @@
/** Base for all 8bpp blitters. */
class Blitter_8bppBase : public Blitter {
public:
uint8_t GetScreenDepth() override { return 8; }
uint8_t GetScreenDepth() override
{
return 8;
}
void DrawColourMappingRect(void *dst, int width, int height, PaletteID pal) override;
void *MoveTo(void *video, int x, int y) override;
void SetPixel(void *video, int x, int y, uint8_t colour) override;

View File

@ -8,11 +8,13 @@
/** @file 8bpp_optimized.cpp Implementation of the optimized 8 bpp blitter. */
#include "../stdafx.h"
#include "../zoom_func.h"
#include "../settings_type.h"
#include "8bpp_optimized.hpp"
#include "../core/math_func.hpp"
#include "../core/mem_func.hpp"
#include "8bpp_optimized.hpp"
#include "../settings_type.h"
#include "../zoom_func.h"
#include "../safeguards.h"
@ -90,7 +92,8 @@ void Blitter_8bppOptimized::Draw(Blitter::BlitterParams *bp, BlitterMode mode, Z
do {
uint m = remap[*src];
if (m != 0) *dst = m;
dst++; src++;
dst++;
src++;
} while (--pixels != 0);
break;
}
@ -113,7 +116,8 @@ void Blitter_8bppOptimized::Draw(Blitter::BlitterParams *bp, BlitterMode mode, Z
default:
MemCpyT(dst, src, pixels);
dst += pixels; src += pixels;
dst += pixels;
src += pixels;
break;
}
}
@ -207,8 +211,10 @@ Sprite *Blitter_8bppOptimized::Encode(const SpriteLoader::SpriteCollection &spri
if (count_dst != nullptr) *count_dst = pixels;
/* Write line-ending */
*dst = 0; dst++;
*dst = 0; dst++;
*dst = 0;
dst++;
*dst = 0;
dst++;
}
}

View File

@ -25,14 +25,21 @@ public:
void Draw(Blitter::BlitterParams *bp, BlitterMode mode, ZoomLevel zoom) override;
Sprite *Encode(const SpriteLoader::SpriteCollection &sprite, SpriteAllocator &allocator) override;
std::string_view GetName() override { return "8bpp-optimized"; }
std::string_view GetName() override
{
return "8bpp-optimized";
}
};
/** Factory for the 8bpp blitter optimised for speed. */
class FBlitter_8bppOptimized : public BlitterFactory {
public:
FBlitter_8bppOptimized() : BlitterFactory("8bpp-optimized", "8bpp Optimized Blitter (compression + all-ZoomLevel cache)") {}
std::unique_ptr<Blitter> CreateInstance() override { return std::make_unique<Blitter_8bppOptimized>(); }
std::unique_ptr<Blitter> CreateInstance() override
{
return std::make_unique<Blitter_8bppOptimized>();
}
};
#endif /* BLITTER_8BPP_OPTIMIZED_HPP */

View File

@ -8,9 +8,11 @@
/** @file 8bpp_simple.cpp Implementation of the simple 8 bpp blitter. */
#include "../stdafx.h"
#include "../zoom_func.h"
#include "8bpp_simple.hpp"
#include "../zoom_func.h"
#include "../safeguards.h"
/** Instantiation of the simple 8bpp blitter factory. */

View File

@ -19,14 +19,21 @@ public:
void Draw(Blitter::BlitterParams *bp, BlitterMode mode, ZoomLevel zoom) override;
Sprite *Encode(const SpriteLoader::SpriteCollection &sprite, SpriteAllocator &allocator) override;
std::string_view GetName() override { return "8bpp-simple"; }
std::string_view GetName() override
{
return "8bpp-simple";
}
};
/** Factory for the most trivial 8bpp blitter. */
class FBlitter_8bppSimple : public BlitterFactory {
public:
FBlitter_8bppSimple() : BlitterFactory("8bpp-simple", "8bpp Simple Blitter (relative slow, but never wrong)") {}
std::unique_ptr<Blitter> CreateInstance() override { return std::make_unique<Blitter_8bppSimple>(); }
std::unique_ptr<Blitter> CreateInstance() override
{
return std::make_unique<Blitter_8bppSimple>();
}
};
#endif /* BLITTER_8BPP_SIMPLE_HPP */

View File

@ -206,7 +206,8 @@ public:
virtual ~Blitter() = default;
template <typename SetPixelT> void DrawLineGeneric(int x, int y, int x2, int y2, int screen_width, int screen_height, int width, int dash, SetPixelT set_pixel);
template <typename SetPixelT>
void DrawLineGeneric(int x, int y, int x2, int y2, int screen_width, int screen_height, int width, int dash, SetPixelT set_pixel);
};
#endif /* BLITTER_BASE_HPP */

View File

@ -10,11 +10,11 @@
#ifndef BLITTER_COMMON_HPP
#define BLITTER_COMMON_HPP
#include "base.hpp"
#include "../core/math_func.hpp"
#include <utility>
#include "../core/math_func.hpp"
#include "base.hpp"
template <typename SetPixelT>
void Blitter::DrawLineGeneric(int x1, int y1, int x2, int y2, int screen_width, int screen_height, int width, int dash, SetPixelT set_pixel)
{

View File

@ -10,10 +10,9 @@
#ifndef BLITTER_FACTORY_HPP
#define BLITTER_FACTORY_HPP
#include "base.hpp"
#include "../debug.h"
#include "../string_func.h"
#include "base.hpp"
/**
* The base factory, keeping track of all blitters.
@ -55,8 +54,7 @@ protected:
* @pre description != nullptr.
* @pre There is no blitter registered with this name.
*/
BlitterFactory(const char *name, const char *description, bool usable = true) :
name(name), description(description)
BlitterFactory(const char *name, const char *description, bool usable = true) : name(name), description(description)
{
if (usable) {
Blitters &blitters = GetBlitters();

View File

@ -8,6 +8,7 @@
/** @file null.cpp A blitter that doesn't blit. */
#include "../stdafx.h"
#include "null.hpp"
#include "../safeguards.h"

View File

@ -15,11 +15,20 @@
/** Blitter that does nothing. */
class Blitter_Null : public Blitter {
public:
uint8_t GetScreenDepth() override { return 0; }
uint8_t GetScreenDepth() override
{
return 0;
}
void Draw(Blitter::BlitterParams *, BlitterMode, ZoomLevel) override {};
void DrawColourMappingRect(void *, int, int, PaletteID) override {};
Sprite *Encode(const SpriteLoader::SpriteCollection &sprite, SpriteAllocator &allocator) override;
void *MoveTo(void *, int, int) override { return nullptr; };
void *MoveTo(void *, int, int) override
{
return nullptr;
};
void SetPixel(void *, int, int, uint8_t) override {};
void DrawRect(void *, int, int, uint8_t) override {};
void DrawLine(void *, int, int, int, int, int, int, uint8_t, int, int) override {};
@ -27,18 +36,34 @@ public:
void CopyToBuffer(const void *, void *, int, int) override {};
void CopyImageToBuffer(const void *, void *, int, int, int) override {};
void ScrollBuffer(void *, int &, int &, int &, int &, int, int) override {};
size_t BufferSize(uint, uint) override { return 0; };
void PaletteAnimate(const Palette &) override { };
Blitter::PaletteAnimation UsePaletteAnimation() override { return Blitter::PaletteAnimation::None; };
std::string_view GetName() override { return "null"; }
size_t BufferSize(uint, uint) override
{
return 0;
};
void PaletteAnimate(const Palette &) override {};
Blitter::PaletteAnimation UsePaletteAnimation() override
{
return Blitter::PaletteAnimation::None;
};
std::string_view GetName() override
{
return "null";
}
};
/** Factory for the blitter that does nothing. */
class FBlitter_Null : public BlitterFactory {
public:
FBlitter_Null() : BlitterFactory("null", "Null Blitter (does nothing)") {}
std::unique_ptr<Blitter> CreateInstance() override { return std::make_unique<Blitter_Null>(); }
std::unique_ptr<Blitter> CreateInstance() override
{
return std::make_unique<Blitter_Null>();
}
};
#endif /* BLITTER_NULL_HPP */

View File

@ -8,9 +8,11 @@
/** @file bmp.cpp Read and write support for bmps. */
#include "stdafx.h"
#include "random_access_file_type.h"
#include "bmp.h"
#include "core/bitmath_func.hpp"
#include "random_access_file_type.h"
#include "safeguards.h"
@ -323,16 +325,24 @@ bool BmpReadBitmap(RandomAccessFile &file, BmpInfo &info, BmpData &data)
switch (info.compression) {
case 0: // no compression
switch (info.bpp) {
case 1: return BmpRead1(file, info, data);
case 4: return BmpRead4(file, info, data);
case 8: return BmpRead8(file, info, data);
case 24: return BmpRead24(file, info, data);
default: NOT_REACHED();
case 1:
return BmpRead1(file, info, data);
case 4:
return BmpRead4(file, info, data);
case 8:
return BmpRead8(file, info, data);
case 24:
return BmpRead24(file, info, data);
default:
NOT_REACHED();
}
break;
case 1: return BmpRead8Rle(file, info, data); // 8-bit RLE compression
case 2: return BmpRead4Rle(file, info, data); // 4-bit RLE compression
default: NOT_REACHED();
case 1:
return BmpRead8Rle(file, info, data); // 8-bit RLE compression
case 2:
return BmpRead4Rle(file, info, data); // 4-bit RLE compression
default:
NOT_REACHED();
}
}

View File

@ -8,6 +8,7 @@
/** @file bootstrap_gui.cpp Barely used user interface for bootstrapping OpenTTD, i.e. downloading the required content. */
#include "stdafx.h"
#include "base_media_base.h"
#include "base_media_graphics.h"
#include "blitter/factory.hpp"
@ -27,7 +28,6 @@
# include "window_func.h"
# include "widgets/bootstrap_widget.h"
# include "table/strings.h"
# include "safeguards.h"
@ -43,12 +43,7 @@ static constexpr NWidgetPart _background_widgets[] = {
/**
* Window description for the background window to prevent smearing.
*/
static WindowDesc _background_desc(
WDP_MANUAL, nullptr, 0, 0,
WC_BOOTSTRAP, WC_NONE,
WindowDefaultFlag::NoClose,
_background_widgets
);
static WindowDesc _background_desc(WDP_MANUAL, nullptr, 0, 0, WC_BOOTSTRAP, WC_NONE, WindowDefaultFlag::NoClose, _background_widgets);
/** The background for the game. */
class BootstrapBackground : public Window {
@ -81,12 +76,7 @@ static constexpr NWidgetPart _nested_bootstrap_errmsg_widgets[] = {
/* clang-format on */
/** Window description for the error window. */
static WindowDesc _bootstrap_errmsg_desc(
WDP_CENTER, nullptr, 0, 0,
WC_BOOTSTRAP, WC_NONE,
{WindowDefaultFlag::Modal, WindowDefaultFlag::NoClose},
_nested_bootstrap_errmsg_widgets
);
static WindowDesc _bootstrap_errmsg_desc(WDP_CENTER, nullptr, 0, 0, WC_BOOTSTRAP, WC_NONE, {WindowDefaultFlag::Modal, WindowDefaultFlag::NoClose}, _nested_bootstrap_errmsg_widgets);
/** The window for a failed bootstrap. */
class BootstrapErrorWindow : public Window {
@ -141,20 +131,13 @@ static constexpr NWidgetPart _nested_bootstrap_download_status_window_widgets[]
/** Window description for the download window */
static WindowDesc _bootstrap_download_status_window_desc(
WDP_CENTER, nullptr, 0, 0,
WC_NETWORK_STATUS_WINDOW, WC_NONE,
{WindowDefaultFlag::Modal, WindowDefaultFlag::NoClose},
_nested_bootstrap_download_status_window_widgets
);
WDP_CENTER, nullptr, 0, 0, WC_NETWORK_STATUS_WINDOW, WC_NONE, {WindowDefaultFlag::Modal, WindowDefaultFlag::NoClose}, _nested_bootstrap_download_status_window_widgets);
/** Window for showing the download status of content */
struct BootstrapContentDownloadStatusWindow : public BaseNetworkContentDownloadStatusWindow {
public:
/** Simple call the constructor of the superclass. */
BootstrapContentDownloadStatusWindow() : BaseNetworkContentDownloadStatusWindow(_bootstrap_download_status_window_desc)
{
}
BootstrapContentDownloadStatusWindow() : BaseNetworkContentDownloadStatusWindow(_bootstrap_download_status_window_desc) {}
void Close([[maybe_unused]] int data = 0) override
{
@ -194,12 +177,7 @@ static constexpr NWidgetPart _bootstrap_query_widgets[] = {
/* clang-format on */
/** The window description for the query. */
static WindowDesc _bootstrap_query_desc(
WDP_CENTER, nullptr, 0, 0,
WC_CONFIRM_POPUP_QUERY, WC_NONE,
WindowDefaultFlag::NoClose,
_bootstrap_query_widgets
);
static WindowDesc _bootstrap_query_desc(WDP_CENTER, nullptr, 0, 0, WC_CONFIRM_POPUP_QUERY, WC_NONE, WindowDefaultFlag::NoClose, _bootstrap_query_widgets);
/** The window for the query. It can't use the generic query window as that uses sprites that don't exist yet. */
class BootstrapAskForDownloadWindow : public Window, ContentCallback {
@ -320,7 +298,9 @@ public:
void OnConnect(bool success) override
{
if (!success) {
EM_ASM({ if (window["openttd_bootstrap_failed"]) openttd_bootstrap_failed(); });
EM_ASM({
if (window["openttd_bootstrap_failed"]) openttd_bootstrap_failed();
});
return;
}
@ -337,7 +317,11 @@ public:
_network_content_client.DownloadSelectedContent(this->total_files, this->total_bytes);
this->downloading = true;
EM_ASM({ if (window["openttd_bootstrap"]) openttd_bootstrap($0, $1); }, this->downloaded_bytes, this->total_bytes);
EM_ASM(
{
if (window["openttd_bootstrap"]) openttd_bootstrap($0, $1);
},
this->downloaded_bytes, this->total_bytes);
}
void OnDownloadProgress(const ContentInfo &, int bytes) override
@ -349,7 +333,11 @@ public:
this->downloaded_bytes += bytes;
}
EM_ASM({ if (window["openttd_bootstrap"]) openttd_bootstrap($0, $1); }, this->downloaded_bytes, this->total_bytes);
EM_ASM(
{
if (window["openttd_bootstrap"]) openttd_bootstrap($0, $1);
},
this->downloaded_bytes, this->total_bytes);
}
void OnDownloadComplete(ContentID) override

View File

@ -8,24 +8,24 @@
/** @file bridge_gui.cpp Graphical user interface for bridge construction */
#include "stdafx.h"
#include "error.h"
#include "core/geometry_func.hpp"
#include "command_func.h"
#include "dropdown_func.h"
#include "error.h"
#include "gfx_func.h"
#include "rail.h"
#include "road.h"
#include "strings_func.h"
#include "window_func.h"
#include "sound_func.h"
#include "gfx_func.h"
#include "tunnelbridge.h"
#include "sortlist_type.h"
#include "dropdown_func.h"
#include "core/geometry_func.hpp"
#include "tunnelbridge_map.h"
#include "road_gui.h"
#include "sortlist_type.h"
#include "sound_func.h"
#include "strings_func.h"
#include "tunnelbridge.h"
#include "tunnelbridge_cmd.h"
#include "tunnelbridge_map.h"
#include "window_func.h"
#include "widgets/bridge_widget.h"
#include "table/strings.h"
#include "safeguards.h"
@ -112,12 +112,16 @@ private:
void BuildBridge(BridgeType type)
{
switch (this->transport_type) {
case TRANSPORT_RAIL: _last_railbridge_type = type; break;
case TRANSPORT_ROAD: _last_roadbridge_type = type; break;
default: break;
case TRANSPORT_RAIL:
_last_railbridge_type = type;
break;
case TRANSPORT_ROAD:
_last_roadbridge_type = type;
break;
default:
break;
}
Command<CMD_BUILD_BRIDGE>::Post(STR_ERROR_CAN_T_BUILD_BRIDGE_HERE, CcBuildBridge,
this->end_tile, this->start_tile, this->transport_type, type, this->road_rail_type);
Command<CMD_BUILD_BRIDGE>::Post(STR_ERROR_CAN_T_BUILD_BRIDGE_HERE, CcBuildBridge, this->end_tile, this->start_tile, this->transport_type, type, this->road_rail_type);
}
/** Sort the builable bridges */
@ -142,24 +146,18 @@ private:
{
/* If the bridge has no meaningful speed limit, don't display it. */
if (bridge_data.spec->speed == UINT16_MAX) {
return _game_mode == GM_EDITOR
? GetString(STR_SELECT_BRIDGE_INFO_NAME, bridge_data.spec->material)
: GetString(STR_SELECT_BRIDGE_INFO_NAME_COST, bridge_data.spec->material, bridge_data.cost);
return _game_mode == GM_EDITOR ? GetString(STR_SELECT_BRIDGE_INFO_NAME, bridge_data.spec->material) :
GetString(STR_SELECT_BRIDGE_INFO_NAME_COST, bridge_data.spec->material, bridge_data.cost);
}
uint64_t packed_velocity = PackVelocity(bridge_data.spec->speed, static_cast<VehicleType>(this->transport_type));
return _game_mode == GM_EDITOR
? GetString(STR_SELECT_BRIDGE_INFO_NAME_MAX_SPEED, bridge_data.spec->material, packed_velocity)
: GetString(STR_SELECT_BRIDGE_INFO_NAME_MAX_SPEED_COST, bridge_data.spec->material, packed_velocity, bridge_data.cost);
return _game_mode == GM_EDITOR ? GetString(STR_SELECT_BRIDGE_INFO_NAME_MAX_SPEED, bridge_data.spec->material, packed_velocity) :
GetString(STR_SELECT_BRIDGE_INFO_NAME_MAX_SPEED_COST, bridge_data.spec->material, packed_velocity, bridge_data.cost);
}
public:
BuildBridgeWindow(WindowDesc &desc, TileIndex start, TileIndex end, TransportType transport_type, uint8_t road_rail_type, GUIBridgeList &&bl) : Window(desc),
start_tile(start),
end_tile(end),
transport_type(transport_type),
road_rail_type(road_rail_type),
bridges(std::move(bl))
BuildBridgeWindow(WindowDesc &desc, TileIndex start, TileIndex end, TransportType transport_type, uint8_t road_rail_type, GUIBridgeList &&bl) :
Window(desc), start_tile(start), end_tile(end), transport_type(transport_type), road_rail_type(road_rail_type), bridges(std::move(bl))
{
this->CreateNestedTree();
this->vscroll = this->GetScrollbar(WID_BBS_SCROLLBAR);
@ -262,7 +260,8 @@ public:
void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
{
switch (widget) {
default: break;
default:
break;
case WID_BBS_BRIDGE_LIST: {
auto it = this->vscroll->GetScrolledItemFromWidget(this->bridges, pt.y, this, WID_BBS_BRIDGE_LIST);
if (it != this->bridges.end()) {
@ -302,11 +301,7 @@ public:
Listing BuildBridgeWindow::last_sorting = {true, 2};
/** Available bridge sorting functions. */
const std::initializer_list<GUIBridgeList::SortFunction * const> BuildBridgeWindow::sorter_funcs = {
&BridgeIndexSorter,
&BridgePriceSorter,
&BridgeSpeedSorter
};
const std::initializer_list<GUIBridgeList::SortFunction *const> BuildBridgeWindow::sorter_funcs = {&BridgeIndexSorter, &BridgePriceSorter, &BridgeSpeedSorter};
/** Widgets of the bridge gui. */
/* clang-format off */
@ -339,12 +334,7 @@ static constexpr NWidgetPart _nested_build_bridge_widgets[] = {
/* clang-format on */
/** Window definition for the rail bridge selection window. */
static WindowDesc _build_bridge_desc(
WDP_AUTO, "build_bridge", 200, 114,
WC_BUILD_BRIDGE, WC_BUILD_TOOLBAR,
WindowDefaultFlag::Construction,
_nested_build_bridge_widgets
);
static WindowDesc _build_bridge_desc(WDP_AUTO, "build_bridge", 200, 114, WC_BUILD_BRIDGE, WC_BUILD_TOOLBAR, WindowDefaultFlag::Construction, _nested_build_bridge_widgets);
/**
* Prepare the data for the build a bridge window.
@ -370,9 +360,14 @@ void ShowBuildBridgeWindow(TileIndex start, TileIndex end, TransportType transpo
*/
BridgeType last_bridge_type = 0;
switch (transport_type) {
case TRANSPORT_ROAD: last_bridge_type = _last_roadbridge_type; break;
case TRANSPORT_RAIL: last_bridge_type = _last_railbridge_type; break;
default: break; // water ways and air routes don't have bridge types
case TRANSPORT_ROAD:
last_bridge_type = _last_roadbridge_type;
break;
case TRANSPORT_RAIL:
last_bridge_type = _last_railbridge_type;
break;
default:
break; // water ways and air routes don't have bridge types
}
if (_ctrl_pressed && CheckBridgeAvailability(last_bridge_type, bridge_len).Succeeded()) {
Command<CMD_BUILD_BRIDGE>::Post(STR_ERROR_CAN_T_BUILD_BRIDGE_HERE, CcBuildBridge, end, start, transport_type, last_bridge_type, road_rail_type);
@ -412,8 +407,11 @@ void ShowBuildBridgeWindow(TileIndex start, TileIndex end, TransportType transpo
break;
}
case TRANSPORT_RAIL: infra_cost = (bridge_len + 2) * RailBuildCost((RailType)road_rail_type); break;
default: break;
case TRANSPORT_RAIL:
infra_cost = (bridge_len + 2) * RailBuildCost((RailType)road_rail_type);
break;
default:
break;
}
bool any_available = false;
@ -433,8 +431,7 @@ void ShowBuildBridgeWindow(TileIndex start, TileIndex end, TransportType transpo
}
}
/* give error cause if no bridges available here*/
if (!any_available)
{
if (!any_available) {
errmsg = type_check.GetErrorMessage();
}
}
@ -442,7 +439,6 @@ void ShowBuildBridgeWindow(TileIndex start, TileIndex end, TransportType transpo
if (!bl.empty()) {
new BuildBridgeWindow(_build_bridge_desc, start, end, transport_type, road_rail_type, std::move(bl));
} else {
ShowErrorMessage(GetEncodedString(STR_ERROR_CAN_T_BUILD_BRIDGE_HERE), GetEncodedString(errmsg),
WL_INFO, TileX(end) * TILE_SIZE, TileY(end) * TILE_SIZE);
ShowErrorMessage(GetEncodedString(STR_ERROR_CAN_T_BUILD_BRIDGE_HERE), GetEncodedString(errmsg), WL_INFO, TileX(end) * TILE_SIZE, TileY(end) * TILE_SIZE);
}
}

View File

@ -8,12 +8,12 @@
/** @file bridge_map.cpp Map accessor functions for bridges. */
#include "stdafx.h"
#include "landscape.h"
#include "tunnelbridge_map.h"
#include "safeguards.h"
/**
* Finds the end of a bridge in the specified direction starting at a middle tile
* @param tile the bridge tile to find the bridge ramp for
@ -31,7 +31,6 @@ static TileIndex GetBridgeEnd(TileIndex tile, DiagDirection dir)
return tile;
}
/**
* Finds the northern end of a bridge starting at a middle tile
* @param t the bridge tile to find the bridge ramp for
@ -41,7 +40,6 @@ TileIndex GetNorthernBridgeEnd(TileIndex t)
return GetBridgeEnd(t, ReverseDiagDir(AxisToDiagDir(GetBridgeAxis(t))));
}
/**
* Finds the southern end of a bridge starting at a middle tile
* @param t the bridge tile to find the bridge ramp for
@ -51,7 +49,6 @@ TileIndex GetSouthernBridgeEnd(TileIndex t)
return GetBridgeEnd(t, AxisToDiagDir(GetBridgeAxis(t)));
}
/**
* Starting at one bridge end finds the other bridge end
* @param tile the bridge ramp tile to find the other bridge ramp for

View File

@ -10,9 +10,9 @@
#ifndef BRIDGE_MAP_H
#define BRIDGE_MAP_H
#include "bridge.h"
#include "rail_map.h"
#include "road_map.h"
#include "bridge.h"
#include "water_map.h"
/**
@ -76,6 +76,7 @@ TileIndex GetSouthernBridgeEnd(TileIndex t);
TileIndex GetOtherBridgeEnd(TileIndex t);
int GetBridgeHeight(TileIndex tile);
/**
* Get the height ('z') of a bridge in pixels.
* @param tile the bridge ramp tile to get the bridge height from

View File

@ -8,41 +8,41 @@
/** @file build_vehicle_gui.cpp GUI for building vehicles. */
#include "stdafx.h"
#include "engine_base.h"
#include "engine_func.h"
#include "station_base.h"
#include "network/network.h"
#include "core/geometry_func.hpp"
#include "articulated_vehicles.h"
#include "textbuf_gui.h"
#include "autoreplace_func.h"
#include "cargotype.h"
#include "command_func.h"
#include "company_func.h"
#include "vehicle_gui.h"
#include "dropdown_func.h"
#include "dropdown_type.h"
#include "engine_base.h"
#include "engine_cmd.h"
#include "engine_func.h"
#include "engine_gui.h"
#include "group.h"
#include "hotkeys.h"
#include "network/network.h"
#include "newgrf_badge.h"
#include "newgrf_badge_gui.h"
#include "newgrf_engine.h"
#include "newgrf_text.h"
#include "group.h"
#include "querystring_gui.h"
#include "station_base.h"
#include "string_func.h"
#include "stringfilter_type.h"
#include "strings_func.h"
#include "window_func.h"
#include "textbuf_gui.h"
#include "timer/timer_game_calendar.h"
#include "vehicle_func.h"
#include "dropdown_type.h"
#include "dropdown_func.h"
#include "engine_gui.h"
#include "cargotype.h"
#include "core/geometry_func.hpp"
#include "autoreplace_func.h"
#include "engine_cmd.h"
#include "train_cmd.h"
#include "vehicle_cmd.h"
#include "vehicle_func.h"
#include "vehicle_gui.h"
#include "window_func.h"
#include "zoom_func.h"
#include "querystring_gui.h"
#include "stringfilter_type.h"
#include "hotkeys.h"
#include "widgets/build_vehicle_widget.h"
#include "table/strings.h"
#include "safeguards.h"
@ -98,12 +98,12 @@ static constexpr NWidgetPart _nested_build_vehicle_widgets[] = {
};
/* clang-format on */
bool _engine_sort_direction; ///< \c false = descending, \c true = ascending.
uint8_t _engine_sort_last_criteria[] = {0, 0, 0, 0}; ///< Last set sort criteria, for each vehicle type.
bool _engine_sort_last_order[] = {false, false, false, false}; ///< Last set direction of the sort order, for each vehicle type.
bool _engine_sort_show_hidden_engines[] = {false, false, false, false}; ///< Last set 'show hidden engines' setting for each vehicle type.
static CargoType _engine_sort_last_cargo_criteria[] = {CargoFilterCriteria::CF_ANY, CargoFilterCriteria::CF_ANY, CargoFilterCriteria::CF_ANY, CargoFilterCriteria::CF_ANY}; ///< Last set filter criteria, for each vehicle type.
static CargoType _engine_sort_last_cargo_criteria[] = {
CargoFilterCriteria::CF_ANY, CargoFilterCriteria::CF_ANY, CargoFilterCriteria::CF_ANY, CargoFilterCriteria::CF_ANY}; ///< Last set filter criteria, for each vehicle type.
/**
* Determines order of engines by engineID
@ -449,7 +449,8 @@ EngList_SortTypeFunction * const _engine_sort_functions[][11] = {{
&EnginePowerVsRunningCostSorter,
&EngineReliabilitySorter,
&TrainEngineCapacitySorter,
}, {
},
{
/* Road vehicles */
&EngineNumberSorter,
&EngineCostSorter,
@ -462,7 +463,8 @@ EngList_SortTypeFunction * const _engine_sort_functions[][11] = {{
&EnginePowerVsRunningCostSorter,
&EngineReliabilitySorter,
&RoadVehEngineCapacitySorter,
}, {
},
{
/* Ships */
&EngineNumberSorter,
&EngineCostSorter,
@ -472,7 +474,8 @@ EngList_SortTypeFunction * const _engine_sort_functions[][11] = {{
&EngineRunningCostSorter,
&EngineReliabilitySorter,
&ShipEngineCapacitySorter,
}, {
},
{
/* Aircraft */
&EngineNumberSorter,
&EngineCostSorter,
@ -499,7 +502,8 @@ const std::initializer_list<const StringID> _engine_sort_listing[] = {{
STR_SORT_BY_POWER_VS_RUNNING_COST,
STR_SORT_BY_RELIABILITY,
STR_SORT_BY_CARGO_CAPACITY,
}, {
},
{
/* Road vehicles */
STR_SORT_BY_ENGINE_ID,
STR_SORT_BY_COST,
@ -512,7 +516,8 @@ const std::initializer_list<const StringID> _engine_sort_listing[] = {{
STR_SORT_BY_POWER_VS_RUNNING_COST,
STR_SORT_BY_RELIABILITY,
STR_SORT_BY_CARGO_CAPACITY,
}, {
},
{
/* Ships */
STR_SORT_BY_ENGINE_ID,
STR_SORT_BY_COST,
@ -522,7 +527,8 @@ const std::initializer_list<const StringID> _engine_sort_listing[] = {{
STR_SORT_BY_RUNNING_COST,
STR_SORT_BY_RELIABILITY,
STR_SORT_BY_CARGO_CAPACITY,
}, {
},
{
/* Aircraft */
STR_SORT_BY_ENGINE_ID,
STR_SORT_BY_COST,
@ -595,8 +601,7 @@ static int DrawRailWagonPurchaseInfo(int left, int right, int y, EngineID engine
/* Wagon weight - (including cargo) */
uint weight = e->GetDisplayWeight();
DrawString(left, right, y,
GetString(STR_PURCHASE_INFO_WEIGHT_CWEIGHT, weight, GetCargoWeight(te.all_capacities, VEH_TRAIN) + weight));
DrawString(left, right, y, GetString(STR_PURCHASE_INFO_WEIGHT_CWEIGHT, weight, GetCargoWeight(te.all_capacities, VEH_TRAIN) + weight));
y += GetCharacterHeight(FS_NORMAL);
/* Wagon speed limit, displayed if above zero */
@ -790,7 +795,6 @@ static int DrawAircraftPurchaseInfo(int left, int right, int y, EngineID engine_
return y;
}
/**
* Try to get the NewGRF engine additional text callback as an optional std::string.
* @param engine The engine whose additional text to get.
@ -858,7 +862,8 @@ int DrawVehiclePurchaseInfo(int left, int right, int y, EngineID engine_number,
bool articulated_cargo = false;
switch (e->type) {
default: NOT_REACHED();
default:
NOT_REACHED();
case VEH_TRAIN:
if (e->u.rail.railveh_type == RAILVEH_WAGON) {
y = DrawRailWagonPurchaseInfo(left, right, y, engine_number, &e->u.rail, te);
@ -914,8 +919,7 @@ int DrawVehiclePurchaseInfo(int left, int right, int y, EngineID engine_number,
/* The NewGRF's name which the vehicle comes from */
const GRFConfig *config = GetGRFConfig(e->GetGRFID());
if (_settings_client.gui.show_newgrf_name && config != nullptr)
{
if (_settings_client.gui.show_newgrf_name && config != nullptr) {
DrawString(left, right, y, config->GetName(), TC_BLACK);
y += GetCharacterHeight(FS_NORMAL);
}
@ -938,7 +942,8 @@ static void DrawEngineBadgeColumn(const Rect &r, int column_group, const GUIBadg
* @param show_count Whether to show the amount of engines or not
* @param selected_group the group to list the engines of
*/
void DrawEngineList(VehicleType type, const Rect &r, const GUIEngineList &eng_list, const Scrollbar &sb, EngineID selected_id, bool show_count, GroupID selected_group, const GUIBadgeClasses &badge_classes)
void DrawEngineList(
VehicleType type, const Rect &r, const GUIEngineList &eng_list, const Scrollbar &sb, EngineID selected_id, bool show_count, GroupID selected_group, const GUIBadgeClasses &badge_classes)
{
static const std::array<int8_t, VehicleType::VEH_COMPANY_END> sprite_y_offsets = {0, 0, -1, -1};
@ -1133,10 +1138,12 @@ enum BuildVehicleHotkeys : int32_t {
/** GUI for building vehicles. */
struct BuildVehicleWindow : Window {
VehicleType vehicle_type = VEH_INVALID; ///< Type of vehicles shown in the window.
union {
RailType railtype; ///< Rail type to show, or #INVALID_RAILTYPE.
RoadType roadtype; ///< Road type to show, or #INVALID_ROADTYPE.
} filter{}; ///< Filter to apply.
bool descending_sort_order = false; ///< Sort direction, @see _engine_sort_direction
uint8_t sort_criteria = 0; ///< Current sort criterium.
bool show_hidden_engines = false; ///< State of the 'show hidden engines' button.
@ -1157,7 +1164,8 @@ struct BuildVehicleWindow : Window {
{
NWidgetCore *widget = this->GetWidget<NWidgetCore>(WID_BV_BUILD);
bool refit = this->sel_engine != EngineID::Invalid() && this->cargo_filter_criteria != CargoFilterCriteria::CF_ANY && this->cargo_filter_criteria != CargoFilterCriteria::CF_NONE && this->cargo_filter_criteria != CargoFilterCriteria::CF_ENGINES;
bool refit = this->sel_engine != EngineID::Invalid() && this->cargo_filter_criteria != CargoFilterCriteria::CF_ANY && this->cargo_filter_criteria != CargoFilterCriteria::CF_NONE &&
this->cargo_filter_criteria != CargoFilterCriteria::CF_ENGINES;
if (refit) refit = Engine::Get(this->sel_engine)->GetDefaultCargoType() != this->cargo_filter_criteria;
if (refit) {
@ -1218,7 +1226,9 @@ struct BuildVehicleWindow : Window {
/* Select the first unshaded engine in the list as default when opening the window */
EngineID engine = EngineID::Invalid();
auto it = std::ranges::find_if(this->eng_list, [](const GUIEngineListItem &item) { return !item.flags.Test(EngineDisplayFlag::Shaded); });
auto it = std::ranges::find_if(this->eng_list, [](const GUIEngineListItem &item) {
return !item.flags.Test(EngineDisplayFlag::Shaded);
});
if (it != this->eng_list.end()) engine = it->engine_id;
this->SelectEngine(engine);
}
@ -1227,7 +1237,8 @@ struct BuildVehicleWindow : Window {
void UpdateFilterByTile()
{
switch (this->vehicle_type) {
default: NOT_REACHED();
default:
NOT_REACHED();
case VEH_TRAIN:
if (this->listview_mode) {
this->filter.railtype = INVALID_RAILTYPE;
@ -1256,10 +1267,14 @@ struct BuildVehicleWindow : Window {
StringID GetCargoFilterLabel(CargoType cargo_type) const
{
switch (cargo_type) {
case CargoFilterCriteria::CF_ANY: return STR_PURCHASE_INFO_ALL_TYPES;
case CargoFilterCriteria::CF_ENGINES: return STR_PURCHASE_INFO_ENGINES_ONLY;
case CargoFilterCriteria::CF_NONE: return STR_PURCHASE_INFO_NONE;
default: return CargoSpec::Get(cargo_type)->name;
case CargoFilterCriteria::CF_ANY:
return STR_PURCHASE_INFO_ALL_TYPES;
case CargoFilterCriteria::CF_ENGINES:
return STR_PURCHASE_INFO_ENGINES_ONLY;
case CargoFilterCriteria::CF_NONE:
return STR_PURCHASE_INFO_NONE;
default:
return CargoSpec::Get(cargo_type)->name;
}
}
@ -1288,7 +1303,8 @@ struct BuildVehicleWindow : Window {
if (!this->listview_mode) {
/* Query for cost and refitted capacity */
auto [ret, veh_id, refit_capacity, refit_mail, cargo_capacities] = Command<CMD_BUILD_VEHICLE>::Do(DoCommandFlag::QueryCost, TileIndex(this->window_number), this->sel_engine, true, cargo, INVALID_CLIENT_ID);
auto [ret, veh_id, refit_capacity, refit_mail, cargo_capacities] =
Command<CMD_BUILD_VEHICLE>::Do(DoCommandFlag::QueryCost, TileIndex(this->window_number), this->sel_engine, true, cargo, INVALID_CLIENT_ID);
if (ret.Succeeded()) {
this->te.cost = ret.GetCost() - e->GetCost();
this->te.capacity = refit_capacity;
@ -1316,7 +1332,8 @@ struct BuildVehicleWindow : Window {
this->eng_list.Filter(this->cargo_filter_criteria);
if (0 == this->eng_list.size()) { // no engine passed through the filter, invalidate the previously selected engine
this->SelectEngine(EngineID::Invalid());
} else if (std::ranges::find(this->eng_list, this->sel_engine, &GUIEngineListItem::engine_id) == this->eng_list.end()) { // previously selected engine didn't pass the filter, select the first engine of the list
} else if (std::ranges::find(this->eng_list, this->sel_engine, &GUIEngineListItem::engine_id) ==
this->eng_list.end()) { // previously selected engine didn't pass the filter, select the first engine of the list
this->SelectEngine(this->eng_list[0].engine_id);
}
}
@ -1508,7 +1525,8 @@ struct BuildVehicleWindow : Window {
GUIEngineList list;
switch (this->vehicle_type) {
default: NOT_REACHED();
default:
NOT_REACHED();
case VEH_TRAIN:
this->GenerateBuildTrainList(list);
GUIEngineListAddChildren(this->eng_list, list);
@ -1628,7 +1646,10 @@ struct BuildVehicleWindow : Window {
const auto it = this->vscroll->GetScrolledItemFromWidget(this->eng_list, pt.y, this, WID_BV_LIST);
if (it != this->eng_list.end()) {
const auto &item = *it;
const Rect r = this->GetWidget<NWidgetBase>(widget)->GetCurrentRect().Shrink(WidgetDimensions::scaled.matrix).WithWidth(WidgetDimensions::scaled.hsep_indent * (item.indent + 1), _current_text_dir == TD_RTL);
const Rect r = this->GetWidget<NWidgetBase>(widget)
->GetCurrentRect()
.Shrink(WidgetDimensions::scaled.matrix)
.WithWidth(WidgetDimensions::scaled.hsep_indent * (item.indent + 1), _current_text_dir == TD_RTL);
if (item.flags.Test(EngineDisplayFlag::HasVariants) && IsInsideMM(r.left, r.right, pt.x)) {
/* toggle folded flag on engine */
assert(item.variant_id != EngineID::Invalid());
@ -1675,7 +1696,8 @@ struct BuildVehicleWindow : Window {
EngineID sel_eng = this->sel_engine;
if (sel_eng != EngineID::Invalid()) {
this->rename_engine = sel_eng;
ShowQueryString(GetString(STR_ENGINE_NAME, PackEngineNameDParam(sel_eng, EngineNameContext::Generic)), STR_QUERY_RENAME_TRAIN_TYPE_CAPTION + this->vehicle_type, MAX_LENGTH_ENGINE_NAME_CHARS, this, CS_ALPHANUMERAL, {QueryStringFlag::EnableDefault, QueryStringFlag::LengthIsInChars});
ShowQueryString(GetString(STR_ENGINE_NAME, PackEngineNameDParam(sel_eng, EngineNameContext::Generic)), STR_QUERY_RENAME_TRAIN_TYPE_CAPTION + this->vehicle_type,
MAX_LENGTH_ENGINE_NAME_CHARS, this, CS_ALPHANUMERAL, {QueryStringFlag::EnableDefault, QueryStringFlag::LengthIsInChars});
}
break;
}
@ -1691,9 +1713,7 @@ struct BuildVehicleWindow : Window {
{
if (!gui_scope) return;
/* When switching to original acceleration model for road vehicles, clear the selected sort criteria if it is not available now. */
if (this->vehicle_type == VEH_ROAD &&
_settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL &&
this->sort_criteria > 7) {
if (this->vehicle_type == VEH_ROAD && _settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL && this->sort_criteria > 7) {
this->sort_criteria = 0;
_engine_sort_last_criteria[VEH_ROAD] = 0;
}
@ -1739,7 +1759,10 @@ struct BuildVehicleWindow : Window {
case WID_BV_LIST:
resize.height = GetEngineListHeight(this->vehicle_type);
size.height = 3 * resize.height;
size.width = std::max(size.width, this->badge_classes.GetTotalColumnsWidth() + GetVehicleImageCellSize(this->vehicle_type, EIT_PURCHASE).extend_left + GetVehicleImageCellSize(this->vehicle_type, EIT_PURCHASE).extend_right + 165) + padding.width;
size.width = std::max(size.width,
this->badge_classes.GetTotalColumnsWidth() + GetVehicleImageCellSize(this->vehicle_type, EIT_PURCHASE).extend_left +
GetVehicleImageCellSize(this->vehicle_type, EIT_PURCHASE).extend_right + 165) +
padding.width;
break;
case WID_BV_PANEL:
@ -1778,16 +1801,7 @@ struct BuildVehicleWindow : Window {
{
switch (widget) {
case WID_BV_LIST:
DrawEngineList(
this->vehicle_type,
r,
this->eng_list,
*this->vscroll,
this->sel_engine,
false,
DEFAULT_GROUP,
this->badge_classes
);
DrawEngineList(this->vehicle_type, r, this->eng_list, *this->vscroll, this->sel_engine, false, DEFAULT_GROUP, this->badge_classes);
break;
case WID_BV_SORT_ASCENDING_DESCENDING:
@ -1885,18 +1899,13 @@ struct BuildVehicleWindow : Window {
return ES_HANDLED;
}
static inline HotkeyList hotkeys{"buildvehicle", {
static inline HotkeyList hotkeys{"buildvehicle",
{
Hotkey('F', "focus_filter_box", BVHK_FOCUS_FILTER_BOX),
}};
};
static WindowDesc _build_vehicle_desc(
WDP_AUTO, "build_vehicle", 240, 268,
WC_BUILD_VEHICLE, WC_NONE,
WindowDefaultFlag::Construction,
_nested_build_vehicle_widgets,
&BuildVehicleWindow::hotkeys
);
static WindowDesc _build_vehicle_desc(WDP_AUTO, "build_vehicle", 240, 268, WC_BUILD_VEHICLE, WC_NONE, WindowDefaultFlag::Construction, _nested_build_vehicle_widgets, &BuildVehicleWindow::hotkeys);
void ShowBuildVehicleWindow(TileIndex tile, VehicleType type)
{

View File

@ -8,6 +8,7 @@
/** @file cachecheck.cpp Check caches. */
#include "stdafx.h"
#include "aircraft.h"
#include "company_base.h"
#include "debug.h"
@ -105,11 +106,20 @@ void CheckCaches()
}
switch (v->type) {
case VEH_TRAIN: Train::From(v)->ConsistChanged(CCF_TRACK); break;
case VEH_ROAD: RoadVehUpdateCache(RoadVehicle::From(v)); break;
case VEH_AIRCRAFT: UpdateAircraftCache(Aircraft::From(v)); break;
case VEH_SHIP: Ship::From(v)->UpdateCache(); break;
default: break;
case VEH_TRAIN:
Train::From(v)->ConsistChanged(CCF_TRACK);
break;
case VEH_ROAD:
RoadVehUpdateCache(RoadVehicle::From(v));
break;
case VEH_AIRCRAFT:
UpdateAircraftCache(Aircraft::From(v));
break;
case VEH_SHIP:
Ship::From(v)->UpdateCache();
break;
default:
break;
}
uint length = 0;

View File

@ -10,9 +10,9 @@
#ifndef CARGO_TYPE_H
#define CARGO_TYPE_H
#include "core/convertible_through_base.hpp"
#include "core/enum_type.hpp"
#include "core/strong_typedef_type.hpp"
#include "core/convertible_through_base.hpp"
/** Globally unique label of a cargo type. */
using CargoLabel = StrongType::Typedef<uint32_t, struct CargoLabelTag, StrongType::Compare>;
@ -103,7 +103,10 @@ namespace CargoFilterCriteria {
};
/** Test whether cargo type is not INVALID_CARGO */
inline bool IsValidCargoType(CargoType cargo) { return cargo != INVALID_CARGO; }
inline bool IsValidCargoType(CargoType cargo)
{
return cargo != INVALID_CARGO;
}
typedef uint64_t CargoTypes;
@ -127,7 +130,9 @@ struct CargoArray : std::array<uint, NUM_CARGO> {
*/
inline uint GetCount() const
{
return std::ranges::count_if(*this, [](uint amount) { return amount != 0; });
return std::ranges::count_if(*this, [](uint amount) {
return amount != 0;
});
}
};

View File

@ -8,8 +8,10 @@
/** @file cargoaction.cpp Implementation of cargo actions. */
#include "stdafx.h"
#include "economy_base.h"
#include "cargoaction.h"
#include "economy_base.h"
#include "station_base.h"
#include "safeguards.h"

View File

@ -23,6 +23,7 @@ protected:
uint max_move; ///< Maximum amount of cargo to be removed with this action.
uint Preprocess(CargoPacket *cp);
bool Postprocess(CargoPacket *cp, uint remove);
public:
CargoRemoval(Tsource *source, uint max_move) : source(source), max_move(max_move) {}
@ -30,7 +31,10 @@ public:
* Returns how much more cargo can be removed with this action.
* @return Amount of cargo this action can still remove.
*/
uint MaxMove() { return this->max_move; }
uint MaxMove()
{
return this->max_move;
}
bool operator()(CargoPacket *cp);
};
@ -43,7 +47,10 @@ protected:
CargoType cargo; ///< The cargo type of the cargo.
public:
CargoDelivery(VehicleCargoList *source, uint max_move, CargoType cargo, CargoPayment *payment, TileIndex current_tile) :
CargoRemoval<VehicleCargoList>(source, max_move), current_tile(current_tile), payment(payment), cargo(cargo) {}
CargoRemoval<VehicleCargoList>(source, max_move), current_tile(current_tile), payment(payment), cargo(cargo)
{
}
bool operator()(CargoPacket *cp);
};
@ -59,6 +66,7 @@ protected:
Tdest *destination; ///< Destination for the cargo.
uint max_move; ///< Maximum amount of cargo to be moved with this action.
CargoPacket *Preprocess(CargoPacket *cp);
public:
CargoMovement(Tsource *source, Tdest *destination, uint max_move) : source(source), destination(destination), max_move(max_move) {}
@ -66,7 +74,10 @@ public:
* Returns how much more cargo can be moved with this action.
* @return Amount of cargo this action can still move.
*/
uint MaxMove() { return this->max_move; }
uint MaxMove()
{
return this->max_move;
}
};
/** Action of transferring cargo from a vehicle to a station. */
@ -75,7 +86,10 @@ protected:
TileIndex current_tile; ///< Current tile cargo unloading is happening.
public:
CargoTransfer(VehicleCargoList *source, StationCargoList *destination, uint max_move, TileIndex current_tile) :
CargoMovement<VehicleCargoList, StationCargoList>(source, destination, max_move), current_tile(current_tile) {}
CargoMovement<VehicleCargoList, StationCargoList>(source, destination, max_move), current_tile(current_tile)
{
}
bool operator()(CargoPacket *cp);
};
@ -85,15 +99,18 @@ protected:
TileIndex current_tile; ///< Current tile cargo loading is happening.
public:
CargoLoad(StationCargoList *source, VehicleCargoList *destination, uint max_move, TileIndex current_tile) :
CargoMovement<StationCargoList, VehicleCargoList>(source, destination, max_move), current_tile(current_tile) {}
CargoMovement<StationCargoList, VehicleCargoList>(source, destination, max_move), current_tile(current_tile)
{
}
bool operator()(CargoPacket *cp);
};
/** Action of reserving cargo from a station to be loaded onto a vehicle. */
class CargoReservation : public CargoLoad {
public:
CargoReservation(StationCargoList *source, VehicleCargoList *destination, uint max_move, TileIndex current_tile) :
CargoLoad(source, destination, max_move, current_tile) {}
CargoReservation(StationCargoList *source, VehicleCargoList *destination, uint max_move, TileIndex current_tile) : CargoLoad(source, destination, max_move, current_tile) {}
bool operator()(CargoPacket *cp);
};
@ -102,17 +119,21 @@ class CargoReturn : public CargoMovement<VehicleCargoList, StationCargoList> {
protected:
TileIndex current_tile; ///< Current tile cargo unloading is happening.
StationID next;
public:
CargoReturn(VehicleCargoList *source, StationCargoList *destination, uint max_move, StationID next, TileIndex current_tile) :
CargoMovement<VehicleCargoList, StationCargoList>(source, destination, max_move), current_tile(current_tile), next(next) {}
CargoMovement<VehicleCargoList, StationCargoList>(source, destination, max_move), current_tile(current_tile), next(next)
{
}
bool operator()(CargoPacket *cp);
};
/** Action of shifting cargo from one vehicle to another. */
class CargoShift : public CargoMovement<VehicleCargoList, VehicleCargoList> {
public:
CargoShift(VehicleCargoList *source, VehicleCargoList *destination, uint max_move) :
CargoMovement<VehicleCargoList, VehicleCargoList>(source, destination, max_move) {}
CargoShift(VehicleCargoList *source, VehicleCargoList *destination, uint max_move) : CargoMovement<VehicleCargoList, VehicleCargoList>(source, destination, max_move) {}
bool operator()(CargoPacket *cp);
};
@ -123,16 +144,22 @@ protected:
StationID avoid;
StationID avoid2;
const GoodsEntry *ge;
public:
CargoReroute(Tlist *source, Tlist *dest, uint max_move, StationID avoid, StationID avoid2, const GoodsEntry *ge) :
CargoMovement<Tlist, Tlist>(source, dest, max_move), avoid(avoid), avoid2(avoid2), ge(ge) {}
CargoMovement<Tlist, Tlist>(source, dest, max_move), avoid(avoid), avoid2(avoid2), ge(ge)
{
}
};
/** Action of rerouting cargo in a station. */
class StationCargoReroute : public CargoReroute<StationCargoList> {
public:
StationCargoReroute(StationCargoList *source, StationCargoList *dest, uint max_move, StationID avoid, StationID avoid2, const GoodsEntry *ge) :
CargoReroute<StationCargoList>(source, dest, max_move, avoid, avoid2, ge) {}
CargoReroute<StationCargoList>(source, dest, max_move, avoid, avoid2, ge)
{
}
bool operator()(CargoPacket *cp);
};
@ -144,6 +171,7 @@ public:
{
assert(this->max_move <= source->ActionCount(VehicleCargoList::MTA_TRANSFER));
}
bool operator()(CargoPacket *cp);
};

View File

@ -8,7 +8,9 @@
/** @file cargomonitor.cpp Implementation of the cargo transport monitoring. */
#include "stdafx.h"
#include "cargomonitor.h"
#include "station_base.h"
#include "safeguards.h"
@ -133,7 +135,8 @@ void AddCargoDelivery(CargoType cargo_type, CompanyID company, uint32_t amount,
if (iter != _cargo_pickups.end()) iter->second += amount;
break;
}
default: break;
default:
break;
}
}
@ -153,4 +156,3 @@ void AddCargoDelivery(CargoType cargo_type, CompanyID company, uint32_t amount,
if (iter != _cargo_deliveries.end()) iter->second += amount;
}
}

View File

@ -10,11 +10,11 @@
#ifndef CARGOMONITOR_H
#define CARGOMONITOR_H
#include "core/overflowsafe_type.hpp"
#include "cargo_type.h"
#include "company_func.h"
#include "industry.h"
#include "town.h"
#include "core/overflowsafe_type.hpp"
struct Station;
@ -34,7 +34,6 @@ typedef std::map<CargoMonitorID, OverflowSafeInt32> CargoMonitorMap;
extern CargoMonitorMap _cargo_pickups;
extern CargoMonitorMap _cargo_deliveries;
/* Constants for encoding and extracting cargo monitors. */
constexpr uint8_t CCB_TOWN_IND_NUMBER_START = 0; ///< Start bit of the town or industry number.
constexpr uint8_t CCB_TOWN_IND_NUMBER_LENGTH = 16; ///< Number of bits of the town or industry number.
@ -47,7 +46,6 @@ constexpr uint8_t CCB_COMPANY_LENGTH = 4; ///< Number of bits of the company fie
static_assert(NUM_CARGO <= (1 << CCB_CARGO_TYPE_LENGTH));
static_assert(MAX_COMPANIES <= (1 << CCB_COMPANY_LENGTH));
/**
* Encode a cargo monitor for pickup or delivery at an industry.
* @param company Company performing the transport.

View File

@ -8,12 +8,13 @@
/** @file cargopacket.cpp Implementation of the cargo packets. */
#include "stdafx.h"
#include "station_base.h"
#include "core/pool_func.hpp"
#include "core/random_func.hpp"
#include "economy_base.h"
#include "cargoaction.h"
#include "economy_base.h"
#include "order_type.h"
#include "station_base.h"
#include "safeguards.h"
@ -24,9 +25,7 @@ INSTANTIATE_POOL_METHODS(CargoPacket)
/**
* Create a new packet for savegame loading.
*/
CargoPacket::CargoPacket()
{
}
CargoPacket::CargoPacket() {}
/**
* Creates a new cargo packet.
@ -36,10 +35,7 @@ CargoPacket::CargoPacket()
* @param source Source of the packet (for subsidies).
* @pre count != 0
*/
CargoPacket::CargoPacket(StationID first_station,uint16_t count, Source source) :
count(count),
source(source),
first_station(first_station)
CargoPacket::CargoPacket(StationID first_station, uint16_t count, Source source) : count(count), source(source), first_station(first_station)
{
assert(count != 0);
}
@ -54,11 +50,7 @@ CargoPacket::CargoPacket(StationID first_station,uint16_t count, Source source)
* @param feeder_share Feeder share the packet has already accumulated.
*/
CargoPacket::CargoPacket(uint16_t count, uint16_t periods_in_transit, StationID first_station, TileIndex source_xy, Money feeder_share) :
count(count),
periods_in_transit(periods_in_transit),
feeder_share(feeder_share),
source_xy(source_xy),
first_station(first_station)
count(count), periods_in_transit(periods_in_transit), feeder_share(feeder_share), source_xy(source_xy), first_station(first_station)
{
assert(count != 0);
}
@ -71,17 +63,11 @@ CargoPacket::CargoPacket(uint16_t count, uint16_t periods_in_transit, StationID
* @param original The original packet we are splitting.
*/
CargoPacket::CargoPacket(uint16_t count, Money feeder_share, CargoPacket &original) :
count(count),
periods_in_transit(original.periods_in_transit),
feeder_share(feeder_share),
source_xy(original.source_xy),
travelled(original.travelled),
source(original.source),
count(count), periods_in_transit(original.periods_in_transit), feeder_share(feeder_share), source_xy(original.source_xy), travelled(original.travelled), source(original.source),
#ifdef WITH_ASSERT
in_vehicle(original.in_vehicle),
#endif /* WITH_ASSERT */
first_station(original.first_station),
next_hop(original.next_hop)
first_station(original.first_station), next_hop(original.next_hop)
{
assert(count != 0);
}
@ -222,8 +208,7 @@ void CargoList<Tinst, Tcont>::InvalidateCache()
template <class Tinst, class Tcont>
/* static */ bool CargoList<Tinst, Tcont>::TryMerge(CargoPacket *icp, CargoPacket *cp)
{
if (Tinst::AreMergable(icp, cp) &&
icp->count + cp->count <= CargoPacket::MAX_COUNT) {
if (Tinst::AreMergable(icp, cp) && icp->count + cp->count <= CargoPacket::MAX_COUNT) {
icp->Merge(cp);
return true;
} else {
@ -255,8 +240,7 @@ template <class Tinst, class Tcont>
void VehicleCargoList::Append(CargoPacket *cp, MoveToAction action)
{
assert(cp != nullptr);
assert(action == MTA_LOAD ||
(action == MTA_KEEP && this->action_counts[MTA_LOAD] == 0));
assert(action == MTA_LOAD || (action == MTA_KEEP && this->action_counts[MTA_LOAD] == 0));
this->AddToMeta(cp, action);
if (this->count == cp->count) {
@ -403,8 +387,7 @@ void VehicleCargoList::AgeCargo()
* @param next_station Next station(s) the vehicle may stop at.
* @return MoveToAction to be performed.
*/
/* static */ VehicleCargoList::MoveToAction VehicleCargoList::ChooseAction(const CargoPacket *cp, StationID cargo_next,
StationID current_station, bool accepted, StationIDStack next_station)
/* static */ VehicleCargoList::MoveToAction VehicleCargoList::ChooseAction(const CargoPacket *cp, StationID cargo_next, StationID current_station, bool accepted, StationIDStack next_station)
{
if (cargo_next == StationID::Invalid()) {
return (accepted && cp->first_station != current_station) ? MTA_DELIVER : MTA_KEEP;
@ -432,7 +415,8 @@ void VehicleCargoList::AgeCargo()
* @param current_tile Current tile the cargo handling is happening on.
* return If any cargo will be unloaded.
*/
bool VehicleCargoList::Stage(bool accepted, StationID current_station, StationIDStack next_station, uint8_t order_flags, const GoodsEntry *ge, CargoType cargo, CargoPayment *payment, TileIndex current_tile)
bool VehicleCargoList::Stage(
bool accepted, StationID current_station, StationIDStack next_station, uint8_t order_flags, const GoodsEntry *ge, CargoType cargo, CargoPayment *payment, TileIndex current_tile)
{
this->AssertCountConsistency();
assert(this->action_counts[MTA_LOAD] == 0);
@ -687,8 +671,7 @@ void StationCargoList::Append(CargoPacket *cp, StationID next)
this->AddToCache(cp);
StationCargoPacketMap::List &list = this->packets[next];
for (StationCargoPacketMap::List::reverse_iterator it(list.rbegin());
it != list.rend(); it++) {
for (StationCargoPacketMap::List::reverse_iterator it(list.rbegin()); it != list.rend(); it++) {
if (StationCargoList::TryMerge(*it, cp)) return;
}

View File

@ -10,15 +10,15 @@
#ifndef CARGOPACKET_H
#define CARGOPACKET_H
#include "core/pool_type.hpp"
#include "economy_type.h"
#include "station_type.h"
#include "order_type.h"
#include "cargo_type.h"
#include "source_type.h"
#include "vehicle_type.h"
#include "core/multimap.hpp"
#include "core/pool_type.hpp"
#include "cargo_type.h"
#include "economy_type.h"
#include "order_type.h"
#include "saveload/saveload.h"
#include "source_type.h"
#include "station_type.h"
#include "vehicle_type.h"
/** Unique identifier for a single cargo packet. */
using CargoPacketID = PoolID<uint32_t, struct CargoPacketIDTag, 0xFFF000, 0xFFFFFF>;
@ -31,7 +31,8 @@ extern CargoPacketPool _cargopacket_pool;
struct GoodsEntry; // forward-declare for Stage() and RerouteStalePackets()
template <class Tinst, class Tcont> class CargoList;
template <class Tinst, class Tcont>
class CargoList;
class StationCargoList; // forward-declare, so we can use it in VehicleCargoList.
extern SaveLoadTable GetCargoPacketDesc();
@ -64,11 +65,13 @@ private:
StationID next_hop = StationID::Invalid(); ///< Station where the cargo wants to go next.
/** The CargoList caches, thus needs to know about it. */
template <class Tinst, class Tcont> friend class CargoList;
template <class Tinst, class Tcont>
friend class CargoList;
friend class VehicleCargoList;
friend class StationCargoList;
/** We want this to be saved, right? */
friend SaveLoadTable GetCargoPacketDesc();
public:
/** Maximum number of items in a single cargo packet. */
static const uint16_t MAX_COUNT = UINT16_MAX;
@ -358,10 +361,7 @@ protected:
*/
inline void AssertCountConsistency() const
{
assert(this->action_counts[MTA_KEEP] +
this->action_counts[MTA_DELIVER] +
this->action_counts[MTA_TRANSFER] +
this->action_counts[MTA_LOAD] == this->count);
assert(this->action_counts[MTA_KEEP] + this->action_counts[MTA_DELIVER] + this->action_counts[MTA_TRANSFER] + this->action_counts[MTA_LOAD] == this->count);
}
void AddToCache(const CargoPacket *cp);
@ -370,8 +370,7 @@ protected:
void AddToMeta(const CargoPacket *cp, MoveToAction action);
void RemoveFromMeta(const CargoPacket *cp, MoveToAction action, uint count);
static MoveToAction ChooseAction(const CargoPacket *cp, StationID cargo_next,
StationID current_station, bool accepted, StationIDStack next_station);
static MoveToAction ChooseAction(const CargoPacket *cp, StationID cargo_next, StationID current_station, bool accepted, StationIDStack next_station);
public:
/** The station cargo list needs to control the unloading. */
@ -503,10 +502,7 @@ public:
*/
static bool AreMergable(const CargoPacket *cp1, const CargoPacket *cp2)
{
return cp1->source_xy == cp2->source_xy &&
cp1->periods_in_transit == cp2->periods_in_transit &&
cp1->first_station == cp2->first_station &&
cp1->source == cp2->source;
return cp1->source_xy == cp2->source_xy && cp1->periods_in_transit == cp2->periods_in_transit && cp1->first_station == cp2->first_station && cp1->source == cp2->source;
}
};
@ -617,10 +613,7 @@ public:
*/
static bool AreMergable(const CargoPacket *cp1, const CargoPacket *cp2)
{
return cp1->source_xy == cp2->source_xy &&
cp1->periods_in_transit == cp2->periods_in_transit &&
cp1->first_station == cp2->first_station &&
cp1->source == cp2->source;
return cp1->source_xy == cp2->source_xy && cp1->periods_in_transit == cp2->periods_in_transit && cp1->first_station == cp2->first_station && cp1->source == cp2->source;
}
};

View File

@ -8,16 +8,18 @@
/** @file cargotype.cpp Implementation of cargoes. */
#include "stdafx.h"
#include "cargotype.h"
#include "core/geometry_func.hpp"
#include "newgrf_cargo.h"
#include "settings_type.h"
#include "string_func.h"
#include "strings_func.h"
#include "settings_type.h"
#include "table/cargo_const.h"
#include "table/sprites.h"
#include "table/strings.h"
#include "table/cargo_const.h"
#include "safeguards.h"
@ -71,13 +73,13 @@ void SetupCargoForClimate(LandscapeType l)
/* Copy from default cargo by label or index. */
auto insert = std::begin(CargoSpec::array);
for (const auto &cl : _default_climate_cargo[to_underlying(l)]) {
struct visitor {
const CargoSpec &operator()(const int &index)
{
/* Copy the default cargo by index. */
return _default_cargo[index];
}
const CargoSpec &operator()(const CargoLabel &label)
{
/* Search for label in default cargo types and copy if found. */
@ -153,7 +155,9 @@ bool IsDefaultCargo(CargoType cargo_type)
if (!cs->IsValid()) return false;
CargoLabel label = cs->label;
return std::any_of(std::begin(_default_cargo_labels), std::end(_default_cargo_labels), [&label](const CargoLabel &cl) { return cl == label; });
return std::any_of(std::begin(_default_cargo_labels), std::end(_default_cargo_labels), [&label](const CargoLabel &cl) {
return cl == label;
});
}
/**

View File

@ -10,13 +10,13 @@
#ifndef CARGOTYPE_H
#define CARGOTYPE_H
#include "economy_type.h"
#include "core/bitmath_func.hpp"
#include "cargo_type.h"
#include "economy_type.h"
#include "gfx_type.h"
#include "landscape_type.h"
#include "newgrf_callbacks.h"
#include "strings_type.h"
#include "landscape_type.h"
#include "core/bitmath_func.hpp"
/** Town growth effect when delivering cargo. */
enum TownAcceptanceEffect : uint8_t {
@ -164,13 +164,30 @@ struct CargoSpec {
this->ValidateIndex();
};
bool operator==(const Iterator &other) const { return this->index == other.index; }
CargoSpec * operator*() const { return CargoSpec::Get(this->index); }
Iterator & operator++() { this->index++; this->ValidateIndex(); return *this; }
bool operator==(const Iterator &other) const
{
return this->index == other.index;
}
CargoSpec *operator*() const
{
return CargoSpec::Get(this->index);
}
Iterator &operator++()
{
this->index++;
this->ValidateIndex();
return *this;
}
private:
size_t index;
void ValidateIndex() { while (this->index < CargoSpec::GetArraySize() && !(CargoSpec::Get(this->index)->IsValid())) this->index++; }
void ValidateIndex()
{
while (this->index < CargoSpec::GetArraySize() && !(CargoSpec::Get(this->index)->IsValid())) this->index++;
}
};
/*
@ -178,10 +195,23 @@ struct CargoSpec {
*/
struct IterateWrapper {
size_t from;
IterateWrapper(size_t from = 0) : from(from) {}
Iterator begin() { return Iterator(this->from); }
Iterator end() { return Iterator(CargoSpec::GetArraySize()); }
bool empty() { return this->begin() == this->end(); }
Iterator begin()
{
return Iterator(this->from);
}
Iterator end()
{
return Iterator(CargoSpec::GetArraySize());
}
bool empty()
{
return this->begin() == this->end();
}
};
/**
@ -189,7 +219,10 @@ struct CargoSpec {
* @param from index of the first CargoSpec to consider
* @return an iterable ensemble of all valid CargoSpec
*/
static IterateWrapper Iterate(size_t from = 0) { return IterateWrapper(from); }
static IterateWrapper Iterate(size_t from = 0)
{
return IterateWrapper(from);
}
/** List of cargo specs for each Town Product Effect. */
static std::array<std::vector<const CargoSpec *>, NUM_TPE> town_production_cargoes;
@ -242,7 +275,10 @@ using SetCargoBitIterator = SetBitIterator<CargoType, CargoTypes>;
/** Comparator to sort CargoType by according to desired order. */
struct CargoTypeComparator {
bool operator() (const CargoType &lhs, const CargoType &rhs) const { return _sorted_cargo_types[lhs] < _sorted_cargo_types[rhs]; }
bool operator()(const CargoType &lhs, const CargoType &rhs) const
{
return _sorted_cargo_types[lhs] < _sorted_cargo_types[rhs];
}
};
#endif /* CARGOTYPE_H */

View File

@ -8,6 +8,7 @@
/** @file cheat.cpp Handling (loading/saving/initializing) of cheats. */
#include "stdafx.h"
#include "cheat_type.h"
#include "safeguards.h"

View File

@ -14,5 +14,4 @@
void ShowCheatWindow();
#endif /* CHEAT_FUNC_H */

View File

@ -8,42 +8,41 @@
/** @file cheat_gui.cpp GUI related to cheating. */
#include "stdafx.h"
#include "command_func.h"
#include "core/geometry_func.hpp"
#include "cheat_type.h"
#include "command_func.h"
#include "company_base.h"
#include "company_func.h"
#include "currency.h"
#include "saveload/saveload.h"
#include "vehicle_base.h"
#include "textbuf_gui.h"
#include "window_gui.h"
#include "string_func.h"
#include "strings_func.h"
#include "window_func.h"
#include "rail_gui.h"
#include "settings_gui.h"
#include "company_gui.h"
#include "currency.h"
#include "error.h"
#include "linkgraph/linkgraphschedule.h"
#include "map_func.h"
#include "tile_map.h"
#include "newgrf.h"
#include "error.h"
#include "misc_cmd.h"
#include "core/geometry_func.hpp"
#include "settings_type.h"
#include "newgrf.h"
#include "rail_gui.h"
#include "saveload/saveload.h"
#include "settings_gui.h"
#include "settings_internal.h"
#include "settings_type.h"
#include "string_func.h"
#include "strings_func.h"
#include "textbuf_gui.h"
#include "tile_map.h"
#include "timer/timer.h"
#include "timer/timer_game_calendar.h"
#include "timer/timer_game_economy.h"
#include "vehicle_base.h"
#include "window_func.h"
#include "window_gui.h"
#include "widgets/cheat_widget.h"
#include "table/sprites.h"
#include "table/strings.h"
#include "safeguards.h"
/**
* The 'amount' to cheat with.
* This variable is semantically a constant value, but because the cheat
@ -249,7 +248,9 @@ struct CheatWindow : Window {
CheatWindow(WindowDesc &desc) : Window(desc)
{
this->sandbox_settings = GetFilteredSettingCollection([](const SettingDesc &sd) { return sd.flags.Test(SettingFlag::Sandbox); });
this->sandbox_settings = GetFilteredSettingCollection([](const SettingDesc &sd) {
return sd.flags.Test(SettingFlag::Sandbox);
});
this->InitNested();
}
@ -261,8 +262,12 @@ struct CheatWindow : Window {
void DrawWidget(const Rect &r, WidgetID widget) const override
{
switch (widget) {
case WID_C_PANEL: DrawCheatWidget(r); break;
case WID_C_SETTINGS: DrawSettingsWidget(r); break;
case WID_C_PANEL:
DrawCheatWidget(r);
break;
case WID_C_SETTINGS:
DrawSettingsWidget(r);
break;
}
}
@ -362,8 +367,8 @@ struct CheatWindow : Window {
DrawDropDownButton(buttons.left, buttons.top, COLOUR_YELLOW, state != 0, editable);
} else {
/* Draw [<][>] boxes for settings of an integer-type */
DrawArrowButtons(buttons.left, buttons.top, COLOUR_YELLOW, state,
editable && value != (sd->flags.Test(SettingFlag::GuiZeroIsSpecial) ? 0 : min_val), editable && static_cast<uint32_t>(value) != max_val);
DrawArrowButtons(buttons.left, buttons.top, COLOUR_YELLOW, state, editable && value != (sd->flags.Test(SettingFlag::GuiZeroIsSpecial) ? 0 : min_val),
editable && static_cast<uint32_t>(value) != max_val);
}
auto [param1, param2] = sd->GetValueParams(value);
DrawString(text.left, text.right, text.top, GetString(sd->GetTitle(), STR_CONFIG_SETTING_VALUE, param1, param2), TC_LIGHT_BLUE);
@ -372,8 +377,12 @@ struct CheatWindow : Window {
void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
{
switch (widget) {
case WID_C_PANEL: UpdateCheatPanelSize(size); break;
case WID_C_SETTINGS: UpdateSettingsPanelSize(size); break;
case WID_C_PANEL:
UpdateCheatPanelSize(size);
break;
case WID_C_SETTINGS:
UpdateSettingsPanelSize(size);
break;
}
}
@ -431,8 +440,12 @@ struct CheatWindow : Window {
void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
{
switch (widget) {
case WID_C_PANEL: CheatPanelClick(pt); break;
case WID_C_SETTINGS: SettingsPanelClick(pt); break;
case WID_C_PANEL:
CheatPanelClick(pt);
break;
case WID_C_SETTINGS:
SettingsPanelClick(pt);
break;
}
}
@ -640,12 +653,7 @@ struct CheatWindow : Window {
};
/** Window description of the cheats GUI. */
static WindowDesc _cheats_desc(
WDP_AUTO, "cheats", 0, 0,
WC_CHEATS, WC_NONE,
{},
_nested_cheat_widgets
);
static WindowDesc _cheats_desc(WDP_AUTO, "cheats", 0, 0, WC_CHEATS, WC_NONE, {}, _nested_cheat_widgets);
/** Open cheat window. */
void ShowCheatWindow()

View File

@ -31,7 +31,8 @@ struct Cheats {
Cheat no_jetcrash; ///< no jet will crash on small airports anymore
Cheat change_date; ///< changes date ingame
Cheat setup_prod; ///< setup raw-material production in game
Cheat edit_max_hl; ///< edit the maximum heightlevel; this is a cheat because of the fact that it needs to reset NewGRF game state and doing so as a simple configuration breaks the expectation of many
Cheat
edit_max_hl; ///< edit the maximum heightlevel; this is a cheat because of the fact that it needs to reset NewGRF game state and doing so as a simple configuration breaks the expectation of many
Cheat station_rating; ///< Fix station ratings at 100%
};

View File

@ -8,18 +8,19 @@
/** @file clear_cmd.cpp Commands related to clear tiles. */
#include "stdafx.h"
#include "core/random_func.hpp"
#include "clear_map.h"
#include "command_func.h"
#include "landscape.h"
#include "genworld.h"
#include "viewport_func.h"
#include "core/random_func.hpp"
#include "newgrf_generic.h"
#include "landscape.h"
#include "landscape_cmd.h"
#include "newgrf_generic.h"
#include "viewport_func.h"
#include "table/strings.h"
#include "table/sprites.h"
#include "table/clear_land.h"
#include "table/sprites.h"
#include "table/strings.h"
#include "safeguards.h"
@ -119,7 +120,8 @@ static void DrawTile_Clear(TileInfo *ti)
break;
case CLEAR_ROCKS:
DrawGroundSprite((HasGrfMiscBit(GrfMiscBit::SecondRockyTileSet) && (TileHash(ti->x, ti->y) & 1) ? SPR_FLAT_ROCKY_LAND_2 : SPR_FLAT_ROCKY_LAND_1) + SlopeToSpriteOffset(ti->tileh), PAL_NONE);
DrawGroundSprite(
(HasGrfMiscBit(GrfMiscBit::SecondRockyTileSet) && (TileHash(ti->x, ti->y) & 1) ? SPR_FLAT_ROCKY_LAND_2 : SPR_FLAT_ROCKY_LAND_1) + SlopeToSpriteOffset(ti->tileh), PAL_NONE);
break;
case CLEAR_FIELDS:
@ -174,7 +176,6 @@ static void UpdateFences(TileIndex tile)
if (dirty) MarkTileDirtyByTile(tile);
}
/** Convert to or from snowy tiles. */
static void TileLoopClearAlps(TileIndex tile)
{
@ -251,9 +252,14 @@ static void TileLoop_Clear(TileIndex tile)
AmbientSoundEffect(tile);
switch (_settings_game.game_creation.landscape) {
case LandscapeType::Tropic: TileLoopClearDesert(tile); break;
case LandscapeType::Arctic: TileLoopClearAlps(tile); break;
default: break;
case LandscapeType::Tropic:
TileLoopClearDesert(tile);
break;
case LandscapeType::Arctic:
TileLoopClearAlps(tile);
break;
default:
break;
}
if (IsSnowTile(tile)) return;

View File

@ -25,7 +25,6 @@ enum ClearGround : uint8_t {
CLEAR_DESERT = 5, ///< 1,3
};
/**
* Test if a tile is covered with snow.
* @param t the tile to check
@ -61,7 +60,6 @@ inline bool IsClearGround(Tile t, ClearGround ct)
return GetClearGround(t) == ct;
}
/**
* Get the density of a non-field clear tile.
* @param t the tile to get the density of
@ -98,7 +96,6 @@ inline void SetClearDensity(Tile t, uint d)
SB(t.m5(), 0, 2, d);
}
/**
* Get the counter used to advance to the next clear density/field type.
* @param t the tile to get the counter of
@ -135,7 +132,6 @@ inline void SetClearCounter(Tile t, uint c)
SB(t.m5(), 5, 3, c);
}
/**
* Sets ground type and density in one go, also sets the counter to 0
* @param t the tile to set the ground type and density for
@ -149,7 +145,6 @@ inline void SetClearGroundDensity(Tile t, ClearGround type, uint density)
t.m5() = 0 << 5 | type << 2 | density;
}
/**
* Get the field type (production stage) of the field
* @param t the field to get the type of
@ -198,7 +193,6 @@ inline void SetIndustryIndexOfField(Tile t, IndustryID i)
t.m2() = i.base();
}
/**
* Is there a fence at the given border?
* @param t the tile to check for fences
@ -210,11 +204,16 @@ inline uint GetFence(Tile t, DiagDirection side)
{
assert(IsClearGround(t, CLEAR_FIELDS));
switch (side) {
default: NOT_REACHED();
case DIAGDIR_SE: return GB(t.m4(), 2, 3);
case DIAGDIR_SW: return GB(t.m4(), 5, 3);
case DIAGDIR_NE: return GB(t.m3(), 5, 3);
case DIAGDIR_NW: return GB(t.m6(), 2, 3);
default:
NOT_REACHED();
case DIAGDIR_SE:
return GB(t.m4(), 2, 3);
case DIAGDIR_SW:
return GB(t.m4(), 5, 3);
case DIAGDIR_NE:
return GB(t.m3(), 5, 3);
case DIAGDIR_NW:
return GB(t.m6(), 2, 3);
}
}
@ -229,15 +228,23 @@ inline void SetFence(Tile t, DiagDirection side, uint h)
{
assert(IsClearGround(t, CLEAR_FIELDS));
switch (side) {
default: NOT_REACHED();
case DIAGDIR_SE: SB(t.m4(), 2, 3, h); break;
case DIAGDIR_SW: SB(t.m4(), 5, 3, h); break;
case DIAGDIR_NE: SB(t.m3(), 5, 3, h); break;
case DIAGDIR_NW: SB(t.m6(), 2, 3, h); break;
default:
NOT_REACHED();
case DIAGDIR_SE:
SB(t.m4(), 2, 3, h);
break;
case DIAGDIR_SW:
SB(t.m4(), 5, 3, h);
break;
case DIAGDIR_NE:
SB(t.m3(), 5, 3, h);
break;
case DIAGDIR_NW:
SB(t.m6(), 2, 3, h);
break;
}
}
/**
* Make a clear tile.
* @param t the tile to make a clear tile
@ -258,7 +265,6 @@ inline void MakeClear(Tile t, ClearGround g, uint density)
t.m8() = 0;
}
/**
* Make a (farm) field tile.
* @param t the tile to make a farm field

View File

@ -8,46 +8,49 @@
/** @file command.cpp Handling of commands. */
#include "stdafx.h"
#include "landscape.h"
#include "error.h"
#include "gui.h"
#include "command_func.h"
#include "network/network_type.h"
#include "network/network.h"
#include "genworld.h"
#include "strings_func.h"
#include "texteff.hpp"
#include "town.h"
#include "timer/timer_game_economy.h"
#include "company_func.h"
#include "company_base.h"
#include "signal_func.h"
#include "core/backup_type.hpp"
#include "object_base.h"
#include "autoreplace_cmd.h"
#include "command_func.h"
#include "company_base.h"
#include "company_cmd.h"
#include "company_func.h"
#include "depot_cmd.h"
#include "economy_cmd.h"
#include "engine_cmd.h"
#include "error.h"
#include "genworld.h"
#include "goal_cmd.h"
#include "group_cmd.h"
#include "gui.h"
#include "industry_cmd.h"
#include "league_cmd.h"
#include "landscape.h"
#include "landscape_cmd.h"
#include "league_cmd.h"
#include "misc/endian_buffer.hpp"
#include "misc_cmd.h"
#include "network/network.h"
#include "network/network_type.h"
#include "news_cmd.h"
#include "object_base.h"
#include "object_cmd.h"
#include "order_cmd.h"
#include "rail_cmd.h"
#include "road_cmd.h"
#include "roadveh_cmd.h"
#include "settings_cmd.h"
#include "signal_func.h"
#include "signs_cmd.h"
#include "station_cmd.h"
#include "story_cmd.h"
#include "string_func.h"
#include "strings_func.h"
#include "subsidy_cmd.h"
#include "terraform_cmd.h"
#include "texteff.hpp"
#include "timer/timer_game_economy.h"
#include "timetable_cmd.h"
#include "town.h"
#include "town_cmd.h"
#include "train_cmd.h"
#include "tree_cmd.h"
@ -56,17 +59,13 @@
#include "viewport_cmd.h"
#include "water_cmd.h"
#include "waypoint_cmd.h"
#include "misc/endian_buffer.hpp"
#include "string_func.h"
#include "table/strings.h"
#include "safeguards.h"
int RecursiveCommandCounter::_counter = 0;
/**
* Define a command with the flags which belongs to it.
*
@ -78,12 +77,17 @@ struct CommandInfo {
CommandFlags flags; ///< The (command) flags to that apply to this command
CommandType type; ///< The type of command.
};
/* Helpers to generate the master command table from the command traits. */
template <typename T>
inline constexpr CommandInfo CommandFromTrait() noexcept { return { T::name, T::flags, T::type }; };
inline constexpr CommandInfo CommandFromTrait() noexcept
{
return {T::name, T::flags, T::type};
};
template <typename T, T... i>
inline constexpr auto MakeCommandsFromTraits(std::integer_sequence<T, i...>) noexcept {
inline constexpr auto MakeCommandsFromTraits(std::integer_sequence<T, i...>) noexcept
{
return std::array<CommandInfo, sizeof...(i)>{{CommandFromTrait<CommandTraits<static_cast<Commands>(i)>>()...}};
}
@ -96,7 +100,6 @@ inline constexpr auto MakeCommandsFromTraits(std::integer_sequence<T, i...>) noe
*/
static constexpr auto _command_proc_table = MakeCommandsFromTraits(std::make_integer_sequence<std::underlying_type_t<Commands>, CMD_END>{});
/**
* This function range-checks a cmd.
*
@ -218,8 +221,7 @@ std::tuple<bool, bool, bool> CommandHelperBase::InternalPostBefore(Commands cmd,
bool only_sending = _networking && !network_command;
if (_pause_mode.Any() && !IsCommandAllowedWhilePaused(cmd) && !estimate_only) {
ShowErrorMessage(GetEncodedString(err_message), GetEncodedString(STR_ERROR_NOT_ALLOWED_WHILE_PAUSED),
WL_INFO, TileX(tile) * TILE_SIZE, TileY(tile) * TILE_SIZE);
ShowErrorMessage(GetEncodedString(err_message), GetEncodedString(STR_ERROR_NOT_ALLOWED_WHILE_PAUSED), WL_INFO, TileX(tile) * TILE_SIZE, TileY(tile) * TILE_SIZE);
return {true, estimate_only, only_sending};
} else {
return {false, estimate_only, only_sending};
@ -260,7 +262,8 @@ void CommandHelperBase::InternalPostResult(CommandCost &res, TileIndex tile, boo
/** Helper to make a desync log for a command. */
void CommandHelperBase::LogCommandExecution(Commands cmd, StringID err_message, const CommandDataBuffer &args, bool failed)
{
Debug(desync, 1, "{}: {:08x}; {:02x}; {:02x}; {:08x}; {:08x}; {} ({})", failed ? "cmdf" : "cmd", (uint32_t)TimerGameEconomy::date.base(), TimerGameEconomy::date_fract, _current_company, cmd, err_message, FormatArrayAsHex(args), GetCommandName(cmd));
Debug(desync, 1, "{}: {:08x}; {:02x}; {:02x}; {:08x}; {:08x}; {} ({})", failed ? "cmdf" : "cmd", (uint32_t)TimerGameEconomy::date.base(), TimerGameEconomy::date_fract, _current_company, cmd,
err_message, FormatArrayAsHex(args), GetCommandName(cmd));
}
/**
@ -299,7 +302,8 @@ bool CommandHelperBase::InternalExecutePrepTest(CommandFlags cmd_flags, TileInde
* @param[in,out] cur_company Backup of current company at start of command execution.
* @return True if test run can go ahead, false on error.
*/
std::tuple<bool, bool, bool> CommandHelperBase::InternalExecuteValidateTestAndPrepExec(CommandCost &res, CommandFlags cmd_flags, bool estimate_only, bool network_command, [[maybe_unused]] Backup<CompanyID> &cur_company)
std::tuple<bool, bool, bool> CommandHelperBase::InternalExecuteValidateTestAndPrepExec(
CommandCost &res, CommandFlags cmd_flags, bool estimate_only, bool network_command, [[maybe_unused]] Backup<CompanyID> &cur_company)
{
BasePersistentStorageArray::SwitchMode(PSM_LEAVE_TESTMODE);
SetTownRatingTestMode(false);
@ -339,7 +343,8 @@ std::tuple<bool, bool, bool> CommandHelperBase::InternalExecuteValidateTestAndPr
* @param[in,out] cur_company Backup of current company at start of command execution.
* @return Final command result.
*/
CommandCost CommandHelperBase::InternalExecuteProcessResult(Commands cmd, CommandFlags cmd_flags, [[maybe_unused]] const CommandCost &res_test, const CommandCost &res_exec, Money extra_cash, TileIndex tile, Backup<CompanyID> &cur_company)
CommandCost CommandHelperBase::InternalExecuteProcessResult(
Commands cmd, CommandFlags cmd_flags, [[maybe_unused]] const CommandCost &res_test, const CommandCost &res_exec, Money extra_cash, TileIndex tile, Backup<CompanyID> &cur_company)
{
BasePersistentStorageArray::SwitchMode(PSM_LEAVE_COMMAND);
@ -392,7 +397,6 @@ CommandCost CommandHelperBase::InternalExecuteProcessResult(Commands cmd, Comman
return res_exec;
}
/**
* Adds the cost of the given command return value to this cost.
* Also takes a possible error message when it is set.

View File

@ -10,12 +10,12 @@
#ifndef COMMAND_FUNC_H
#define COMMAND_FUNC_H
#include "command_type.h"
#include "network/network_type.h"
#include "company_type.h"
#include "company_func.h"
#include "core/backup_type.hpp"
#include "command_type.h"
#include "company_func.h"
#include "company_type.h"
#include "misc/endian_buffer.hpp"
#include "network/network_type.h"
#include "tile_map.h"
/**
@ -56,11 +56,22 @@ static constexpr inline DoCommandFlags CommandFlagsToDCFlags(CommandFlags cmd_fl
/** Helper class to keep track of command nesting level. */
struct RecursiveCommandCounter {
RecursiveCommandCounter() noexcept { _counter++; }
~RecursiveCommandCounter() noexcept { _counter--; }
RecursiveCommandCounter() noexcept
{
_counter++;
}
~RecursiveCommandCounter() noexcept
{
_counter--;
}
/** Are we in the top-level command execution? */
bool IsTopLevel() const { return _counter == 1; }
bool IsTopLevel() const
{
return _counter == 1;
}
private:
static int _counter;
};
@ -80,7 +91,8 @@ private:
# define SILENCE_GCC_FUNCTION_POINTER_CAST
#endif
template <Commands TCmd, typename T, bool THasTile> struct CommandHelper;
template <Commands TCmd, typename T, bool THasTile>
struct CommandHelper;
class CommandHelperBase {
protected:
@ -90,7 +102,8 @@ protected:
static void InternalPostResult(CommandCost &res, TileIndex tile, bool estimate_only, bool only_sending, StringID err_message, bool my_cmd);
static bool InternalExecutePrepTest(CommandFlags cmd_flags, TileIndex tile, Backup<CompanyID> &cur_company);
static std::tuple<bool, bool, bool> InternalExecuteValidateTestAndPrepExec(CommandCost &res, CommandFlags cmd_flags, bool estimate_only, bool network_command, Backup<CompanyID> &cur_company);
static CommandCost InternalExecuteProcessResult(Commands cmd, CommandFlags cmd_flags, const CommandCost &res_test, const CommandCost &res_exec, Money extra_cash, TileIndex tile, Backup<CompanyID> &cur_company);
static CommandCost InternalExecuteProcessResult(
Commands cmd, CommandFlags cmd_flags, const CommandCost &res_test, const CommandCost &res_exec, Money extra_cash, TileIndex tile, Backup<CompanyID> &cur_company);
static void LogCommandExecution(Commands cmd, StringID err_message, const CommandDataBuffer &args, bool failed);
};
@ -169,19 +182,30 @@ public:
* @param err_message Message prefix to show on error
* @param args Parameters for the command
*/
static inline bool Post(StringID err_message, Targs... args) { return Post<CommandCallback>(err_message, nullptr, std::forward<Targs>(args)...); }
static inline bool Post(StringID err_message, Targs... args)
{
return Post<CommandCallback>(err_message, nullptr, std::forward<Targs>(args)...);
}
/**
* Shortcut for the long Post when not using an error message.
* @param callback A callback function to call after the command is finished
* @param args Parameters for the command
*/
template <typename Tcallback>
static inline bool Post(Tcallback *callback, Targs... args) { return Post((StringID)0, callback, std::forward<Targs>(args)...); }
static inline bool Post(Tcallback *callback, Targs... args)
{
return Post((StringID)0, callback, std::forward<Targs>(args)...);
}
/**
* Shortcut for the long Post when not using a callback or an error message.
* @param args Parameters for the command
*/
static inline bool Post(Targs... args) { return Post<CommandCallback>((StringID)0, nullptr, std::forward<Targs>(args)...); }
static inline bool Post(Targs... args)
{
return Post<CommandCallback>((StringID)0, nullptr, std::forward<Targs>(args)...);
}
/**
* Top-level network safe command execution for the current company.
@ -264,7 +288,11 @@ protected:
template <template <typename...> typename Tt, typename T1, typename... Ts>
static inline Tt<Ts...> RemoveFirstTupleElement(const Tt<T1, Ts...> &tuple)
{
return std::apply([](auto &&, const auto&... args) { return std::tie(args...); }, tuple);
return std::apply(
[](auto &&, const auto &...args) {
return std::tie(args...);
},
tuple);
}
template <typename Tcallback>
@ -421,8 +449,7 @@ protected:
* @tparam Targs The command parameter types.
*/
template <Commands Tcmd, typename Tret, typename... Targs>
struct CommandHelper<Tcmd, Tret(*)(DoCommandFlags, Targs...), false> : CommandHelper<Tcmd, Tret(*)(DoCommandFlags, Targs...), true>
{
struct CommandHelper<Tcmd, Tret (*)(DoCommandFlags, Targs...), false> : CommandHelper<Tcmd, Tret (*)(DoCommandFlags, Targs...), true> {
/* Do not allow Post without explicit location. */
static inline bool Post(StringID err_message, Targs... args) = delete;
template <typename Tcallback>
@ -437,7 +464,11 @@ struct CommandHelper<Tcmd, Tret(*)(DoCommandFlags, Targs...), false> : CommandHe
* @param location Tile location for user feedback.
* @param args Parameters for the command
*/
static inline bool Post(StringID err_message, TileIndex location, Targs... args) { return Post<CommandCallback>(err_message, nullptr, location, std::forward<Targs>(args)...); }
static inline bool Post(StringID err_message, TileIndex location, Targs... args)
{
return Post<CommandCallback>(err_message, nullptr, location, std::forward<Targs>(args)...);
}
/**
* Shortcut for Post when not using an error message.
* @param callback A callback function to call after the command is finished
@ -445,13 +476,20 @@ struct CommandHelper<Tcmd, Tret(*)(DoCommandFlags, Targs...), false> : CommandHe
* @param args Parameters for the command
*/
template <typename Tcallback>
static inline bool Post(Tcallback *callback, TileIndex location, Targs... args) { return Post((StringID)0, callback, location, std::forward<Targs>(args)...); }
static inline bool Post(Tcallback *callback, TileIndex location, Targs... args)
{
return Post((StringID)0, callback, location, std::forward<Targs>(args)...);
}
/**
* Shortcut for Post when not using a callback or an error message.
* @param location Tile location for user feedback.
* @param args Parameters for the command*
*/
static inline bool Post(TileIndex location, Targs... args) { return Post<CommandCallback>((StringID)0, nullptr, location, std::forward<Targs>(args)...); }
static inline bool Post(TileIndex location, Targs... args)
{
return Post<CommandCallback>((StringID)0, nullptr, location, std::forward<Targs>(args)...);
}
/**
* Post variant that takes a TileIndex (for error window location and text effects) for

View File

@ -181,7 +181,11 @@ public:
};
CommandCost CommandCostWithParam(StringID str, uint64_t value);
CommandCost CommandCostWithParam(StringID str, ConvertibleThroughBase auto value) { return CommandCostWithParam(str, value.base()); }
CommandCost CommandCostWithParam(StringID str, ConvertibleThroughBase auto value)
{
return CommandCostWithParam(str, value.base());
}
/**
* List of commands.
@ -393,6 +397,7 @@ enum DoCommandFlag : uint8_t {
NoModifyTownRating, ///< do not change town rating
ForceClearTile, ///< do not only remove the object on the tile, but also clear any water left on it
};
using DoCommandFlags = EnumBitSet<DoCommandFlag, uint16_t>;
/**
@ -439,8 +444,9 @@ enum CommandPauseLevel : uint8_t {
CMDPL_ALL_ACTIONS, ///< All actions may be executed.
};
template <typename T>
struct CommandFunctionTraitHelper;
template <typename T> struct CommandFunctionTraitHelper;
template <typename... Targs>
struct CommandFunctionTraitHelper<CommandCost (*)(DoCommandFlags, Targs...)> {
using Args = std::tuple<std::decay_t<Targs>...>;
@ -448,6 +454,7 @@ struct CommandFunctionTraitHelper<CommandCost(*)(DoCommandFlags, Targs...)> {
using CbArgs = Args;
using CbProcType = void (*)(Commands, const CommandCost &);
};
template <template <typename...> typename Tret, typename... Tretargs, typename... Targs>
struct CommandFunctionTraitHelper<Tret<CommandCost, Tretargs...> (*)(DoCommandFlags, Targs...)> {
using Args = std::tuple<std::decay_t<Targs>...>;
@ -457,7 +464,8 @@ struct CommandFunctionTraitHelper<Tret<CommandCost, Tretargs...>(*)(DoCommandFla
};
/** Defines the traits of a command. */
template <Commands Tcmd> struct CommandTraits;
template <Commands Tcmd>
struct CommandTraits;
#define DEF_CMD_TRAIT(cmd_, proc_, flags_, type_) \
template <> struct CommandTraits<cmd_> { \

View File

@ -10,13 +10,13 @@
#ifndef COMPANY_BASE_H
#define COMPANY_BASE_H
#include "road_type.h"
#include "livery.h"
#include "autoreplace_type.h"
#include "group.h"
#include "livery.h"
#include "road_type.h"
#include "settings_type.h"
#include "tile_type.h"
#include "timer/timer_game_economy.h"
#include "settings_type.h"
#include "group.h"
static const Money COMPANY_MAX_LOAN_DEFAULT = INT64_MIN;

View File

@ -8,40 +8,41 @@
/** @file company_cmd.cpp Handling of companies. */
#include "stdafx.h"
#include "company_cmd.h"
#include "core/backup_type.hpp"
#include "core/pool_func.hpp"
#include "ai/ai.hpp"
#include "ai/ai_config.hpp"
#include "ai/ai_instance.hpp"
#include "command_func.h"
#include "company_base.h"
#include "company_func.h"
#include "company_gui.h"
#include "core/backup_type.hpp"
#include "town.h"
#include "news_func.h"
#include "command_func.h"
#include "network/network.h"
#include "network/network_func.h"
#include "network/network_base.h"
#include "network/network_admin.h"
#include "ai/ai.hpp"
#include "ai/ai_instance.hpp"
#include "ai/ai_config.hpp"
#include "company_manager_face.h"
#include "window_func.h"
#include "strings_func.h"
#include "sound_func.h"
#include "rail.h"
#include "core/pool_func.hpp"
#include "settings_func.h"
#include "vehicle_base.h"
#include "vehicle_func.h"
#include "smallmap_gui.h"
#include "game/game.hpp"
#include "goal_base.h"
#include "network/network.h"
#include "network/network_admin.h"
#include "network/network_base.h"
#include "network/network_func.h"
#include "news_func.h"
#include "rail.h"
#include "settings_func.h"
#include "smallmap_gui.h"
#include "sound_func.h"
#include "story_base.h"
#include "company_cmd.h"
#include "strings_func.h"
#include "timer/timer.h"
#include "timer/timer_game_economy.h"
#include "timer/timer_game_tick.h"
#include "town.h"
#include "vehicle_base.h"
#include "vehicle_func.h"
#include "window_func.h"
#include "widgets/statusbar_widget.h"
#include "table/strings.h"
#include "safeguards.h"
@ -190,12 +191,21 @@ static bool IsValidCompanyManagerFace(CompanyManagerFace cmf)
if (!AreCompanyManagerFaceBitsValid(cmf, CMFV_EYE_COLOUR, ge)) return false;
for (CompanyManagerFaceVariable cmfv = CMFV_CHEEKS; cmfv < CMFV_END; cmfv++) {
switch (cmfv) {
case CMFV_MOUSTACHE: if (!has_moustache) continue; break;
case CMFV_MOUSTACHE:
if (!has_moustache) continue;
break;
case CMFV_LIPS:
case CMFV_NOSE: if (has_moustache) continue; break;
case CMFV_TIE_EARRING: if (!has_tie_earring) continue; break;
case CMFV_GLASSES: if (!has_glasses) continue; break;
default: break;
case CMFV_NOSE:
if (has_moustache) continue;
break;
case CMFV_TIE_EARRING:
if (!has_tie_earring) continue;
break;
case CMFV_GLASSES:
if (!has_glasses) continue;
break;
default:
break;
}
if (!AreCompanyManagerFaceBitsValid(cmf, cmfv, ge)) return false;
}
@ -276,17 +286,10 @@ static void SubtractMoneyFromAnyCompany(Company *c, const CommandCost &cost)
c->money -= cost.GetCost();
c->yearly_expenses[0][cost.GetExpensesType()] += cost.GetCost();
if (HasBit(1 << EXPENSES_TRAIN_REVENUE |
1 << EXPENSES_ROADVEH_REVENUE |
1 << EXPENSES_AIRCRAFT_REVENUE |
1 << EXPENSES_SHIP_REVENUE, cost.GetExpensesType())) {
if (HasBit(1 << EXPENSES_TRAIN_REVENUE | 1 << EXPENSES_ROADVEH_REVENUE | 1 << EXPENSES_AIRCRAFT_REVENUE | 1 << EXPENSES_SHIP_REVENUE, cost.GetExpensesType())) {
c->cur_economy.income -= cost.GetCost();
} else if (HasBit(1 << EXPENSES_TRAIN_RUN |
1 << EXPENSES_ROADVEH_RUN |
1 << EXPENSES_AIRCRAFT_RUN |
1 << EXPENSES_SHIP_RUN |
1 << EXPENSES_PROPERTY |
1 << EXPENSES_LOAN_INTEREST, cost.GetExpensesType())) {
} else if (HasBit(1 << EXPENSES_TRAIN_RUN | 1 << EXPENSES_ROADVEH_RUN | 1 << EXPENSES_AIRCRAFT_RUN | 1 << EXPENSES_SHIP_RUN | 1 << EXPENSES_PROPERTY | 1 << EXPENSES_LOAN_INTEREST,
cost.GetExpensesType())) {
c->cur_economy.expenses -= cost.GetCost();
}
@ -431,8 +434,7 @@ set_name:;
if (c->is_ai) {
auto cni = std::make_unique<CompanyNewsInformation>(STR_NEWS_COMPANY_LAUNCH_TITLE, c);
EncodedString headline = GetEncodedString(STR_NEWS_COMPANY_LAUNCH_DESCRIPTION, cni->company_name, t->index);
AddNewsItem(std::move(headline),
NewsType::CompanyInfo, NewsStyle::Company, {}, c->last_build_coordinate, {}, std::move(cni));
AddNewsItem(std::move(headline), NewsType::CompanyInfo, NewsStyle::Company, {}, c->last_build_coordinate, {}, std::move(cni));
}
return;
}
@ -725,9 +727,7 @@ static void HandleBankruptcyTakeover(Company *c)
/* Ask the company with the highest performance history first */
for (Company *c2 : Company::Iterate()) {
if (c2->bankrupt_asked.None() && // Don't ask companies going bankrupt themselves
!c->bankrupt_asked.Test(c2->index) &&
best_performance < c2->old_economy[1].performance_history &&
CheckTakeoverVehicleLimit(c2->index, c->index)) {
!c->bankrupt_asked.Test(c2->index) && best_performance < c2->old_economy[1].performance_history && CheckTakeoverVehicleLimit(c2->index, c->index)) {
best_performance = c2->old_economy[1].performance_history;
best = c2;
}
@ -791,8 +791,7 @@ void OnTick_Companies()
* A year has passed, update the economic data of all companies, and perhaps show the
* financial overview window of the local company.
*/
static IntervalTimer<TimerGameEconomy> _economy_companies_yearly({TimerGameEconomy::YEAR, TimerGameEconomy::Priority::COMPANY}, [](auto)
{
static IntervalTimer<TimerGameEconomy> _economy_companies_yearly({TimerGameEconomy::YEAR, TimerGameEconomy::Priority::COMPANY}, [](auto) {
/* Copy statistics */
for (Company *c : Company::Iterate()) {
/* Move expenses to previous years. */
@ -831,7 +830,6 @@ CompanyNewsInformation::CompanyNewsInformation(StringID title, const Company *c,
this->title = title;
this->colour = c->colour;
this->face = c->face;
}
/**
@ -967,7 +965,8 @@ CommandCost CmdCompanyCtrl(DoCommandFlags flags, CompanyCtrlAction cca, CompanyI
break;
}
default: return CMD_ERROR;
default:
return CMD_ERROR;
}
InvalidateWindowClassesData(WC_GAME_OPTIONS);
@ -1254,11 +1253,16 @@ int CompanyServiceInterval(const Company *c, VehicleType type)
{
const VehicleDefaultSettings *vds = (c == nullptr) ? &_settings_client.company.vehicle : &c->settings.vehicle;
switch (type) {
default: NOT_REACHED();
case VEH_TRAIN: return vds->servint_trains;
case VEH_ROAD: return vds->servint_roadveh;
case VEH_AIRCRAFT: return vds->servint_aircraft;
case VEH_SHIP: return vds->servint_ships;
default:
NOT_REACHED();
case VEH_TRAIN:
return vds->servint_trains;
case VEH_ROAD:
return vds->servint_roadveh;
case VEH_AIRCRAFT:
return vds->servint_aircraft;
case VEH_SHIP:
return vds->servint_ships;
}
}

View File

@ -8,53 +8,51 @@
/** @file company_gui.cpp %Company related GUIs. */
#include "stdafx.h"
#include "currency.h"
#include "error.h"
#include "gui.h"
#include "window_gui.h"
#include "textbuf_gui.h"
#include "viewport_func.h"
#include "company_func.h"
#include "command_func.h"
#include "network/network.h"
#include "network/network_gui.h"
#include "network/network_func.h"
#include "newgrf.h"
#include "company_manager_face.h"
#include "strings_func.h"
#include "timer/timer_game_economy.h"
#include "dropdown_type.h"
#include "tilehighlight_func.h"
#include "company_base.h"
#include "core/geometry_func.hpp"
#include "command_func.h"
#include "company_base.h"
#include "company_cmd.h"
#include "company_func.h"
#include "company_manager_face.h"
#include "currency.h"
#include "dropdown_common_type.h"
#include "dropdown_type.h"
#include "economy_cmd.h"
#include "engine_base.h"
#include "error.h"
#include "group_cmd.h"
#include "group_gui.h"
#include "gui.h"
#include "misc_cmd.h"
#include "network/network.h"
#include "network/network_func.h"
#include "network/network_gui.h"
#include "newgrf.h"
#include "object_cmd.h"
#include "object_type.h"
#include "rail.h"
#include "road.h"
#include "engine_base.h"
#include "window_func.h"
#include "road_func.h"
#include "water.h"
#include "station_func.h"
#include "zoom_func.h"
#include "sortlist_type.h"
#include "company_cmd.h"
#include "economy_cmd.h"
#include "group_cmd.h"
#include "group_gui.h"
#include "misc_cmd.h"
#include "object_cmd.h"
#include "station_func.h"
#include "strings_func.h"
#include "textbuf_gui.h"
#include "tilehighlight_func.h"
#include "timer/timer.h"
#include "timer/timer_game_economy.h"
#include "timer/timer_window.h"
#include "viewport_func.h"
#include "water.h"
#include "window_func.h"
#include "window_gui.h"
#include "zoom_func.h"
#include "widgets/company_widget.h"
#include "table/strings.h"
#include "dropdown_common_type.h"
#include "safeguards.h"
/** Company GUI constants. */
static void DoSelectCompanyManagerFace(Window *parent);
static void ShowCompanyInfrastructure(CompanyID company);
@ -89,9 +87,7 @@ struct ExpensesList {
const StringID title; ///< StringID of list title.
const std::initializer_list<ExpensesType> &items; ///< List of expenses types.
ExpensesList(StringID title, const std::initializer_list<ExpensesType> &list) : title(title), items(list)
{
}
ExpensesList(StringID title, const std::initializer_list<ExpensesType> &list) : title(title), items(list) {}
uint GetHeight() const
{
@ -253,7 +249,6 @@ static Money DrawYearCategory(const Rect &r, int start_y, const ExpensesList &li
return sum;
}
/**
* Draw a column with prices.
* @param r Available space for drawing.
@ -525,7 +520,9 @@ struct CompanyFinancesWindow : Window {
const Company *c = Company::Get(this->window_number);
const Expenses &expenses = c->yearly_expenses[NUM_PERIODS - period - 1];
/* Show expenses column if it has any non-zero value in it. */
if (std::ranges::any_of(expenses, [](const Money &value) { return value != 0; })) {
if (std::ranges::any_of(expenses, [](const Money &value) {
return value != 0;
})) {
this->first_visible = period;
break;
}
@ -554,12 +551,7 @@ struct CompanyFinancesWindow : Window {
/** First conservative estimate of the maximum amount of money */
Money CompanyFinancesWindow::max_money = INT32_MAX;
static WindowDesc _company_finances_desc(
WDP_AUTO, "company_finances", 0, 0,
WC_FINANCES, WC_NONE,
{},
_nested_company_finances_widgets
);
static WindowDesc _company_finances_desc(WDP_AUTO, "company_finances", 0, 0, WC_FINANCES, WC_NONE, {}, _nested_company_finances_widgets);
/**
* Open the finances window of a company.
@ -577,11 +569,28 @@ void ShowCompanyFinances(CompanyID company)
/* Association of liveries to livery classes */
static const LiveryClass _livery_class[LS_END] = {
LC_OTHER,
LC_RAIL, LC_RAIL, LC_RAIL, LC_RAIL, LC_RAIL, LC_RAIL, LC_RAIL, LC_RAIL, LC_RAIL, LC_RAIL, LC_RAIL, LC_RAIL, LC_RAIL,
LC_ROAD, LC_ROAD,
LC_SHIP, LC_SHIP,
LC_AIRCRAFT, LC_AIRCRAFT, LC_AIRCRAFT,
LC_ROAD, LC_ROAD,
LC_RAIL,
LC_RAIL,
LC_RAIL,
LC_RAIL,
LC_RAIL,
LC_RAIL,
LC_RAIL,
LC_RAIL,
LC_RAIL,
LC_RAIL,
LC_RAIL,
LC_RAIL,
LC_RAIL,
LC_ROAD,
LC_ROAD,
LC_SHIP,
LC_SHIP,
LC_AIRCRAFT,
LC_AIRCRAFT,
LC_AIRCRAFT,
LC_ROAD,
LC_ROAD,
};
/**
@ -592,7 +601,8 @@ template <SpriteID TSprite = SPR_SQUARE>
class DropDownListColourItem : public DropDownIcon<DropDownString<DropDownListItem>> {
public:
DropDownListColourItem(int colour, bool masked) :
DropDownIcon<DropDownString<DropDownListItem>>(TSprite, GetColourPalette(static_cast<Colours>(colour % COLOUR_END)), GetString(colour < COLOUR_END ? (STR_COLOUR_DARK_BLUE + colour) : STR_COLOUR_DEFAULT), colour, masked)
DropDownIcon<DropDownString<DropDownListItem>>(
TSprite, GetColourPalette(static_cast<Colours>(colour % COLOUR_END)), GetString(colour < COLOUR_END ? (STR_COLOUR_DARK_BLUE + colour) : STR_COLOUR_DEFAULT), colour, masked)
{
}
};
@ -719,11 +729,20 @@ public:
this->RaiseWidget(WID_SCL_CLASS_GENERAL + this->livery_class);
const Group *g = Group::Get(group);
switch (g->vehicle_type) {
case VEH_TRAIN: this->livery_class = LC_GROUP_RAIL; break;
case VEH_ROAD: this->livery_class = LC_GROUP_ROAD; break;
case VEH_SHIP: this->livery_class = LC_GROUP_SHIP; break;
case VEH_AIRCRAFT: this->livery_class = LC_GROUP_AIRCRAFT; break;
default: NOT_REACHED();
case VEH_TRAIN:
this->livery_class = LC_GROUP_RAIL;
break;
case VEH_ROAD:
this->livery_class = LC_GROUP_ROAD;
break;
case VEH_SHIP:
this->livery_class = LC_GROUP_SHIP;
break;
case VEH_AIRCRAFT:
this->livery_class = LC_GROUP_AIRCRAFT;
break;
default:
NOT_REACHED();
}
this->sel = group.base();
this->LowerWidget(WID_SCL_CLASS_GENERAL + this->livery_class);
@ -882,12 +901,14 @@ public:
/* Text below the first dropdown. */
DrawSprite(SPR_SQUARE, GetColourPalette(livery.colour1), pri_squ.left, y + square_offs);
DrawString(pri.left, pri.right, y + text_offs, (is_default_scheme || HasBit(livery.in_use, 0)) ? STR_COLOUR_DARK_BLUE + livery.colour1 : STR_COLOUR_DEFAULT, is_selected ? TC_WHITE : TC_GOLD);
DrawString(
pri.left, pri.right, y + text_offs, (is_default_scheme || HasBit(livery.in_use, 0)) ? STR_COLOUR_DARK_BLUE + livery.colour1 : STR_COLOUR_DEFAULT, is_selected ? TC_WHITE : TC_GOLD);
/* Text below the second dropdown. */
if (sec.right > sec.left) { // Second dropdown has non-zero size.
DrawSprite(SPR_SQUARE, GetColourPalette(livery.colour2), sec_squ.left, y + square_offs);
DrawString(sec.left, sec.right, y + text_offs, (is_default_scheme || HasBit(livery.in_use, 1)) ? STR_COLOUR_DARK_BLUE + livery.colour2 : STR_COLOUR_DEFAULT, is_selected ? TC_WHITE : TC_GOLD);
DrawString(
sec.left, sec.right, y + text_offs, (is_default_scheme || HasBit(livery.in_use, 1)) ? STR_COLOUR_DARK_BLUE + livery.colour2 : STR_COLOUR_DEFAULT, is_selected ? TC_WHITE : TC_GOLD);
}
y += this->line_height;
@ -1103,12 +1124,7 @@ static constexpr NWidgetPart _nested_select_company_livery_widgets[] = {
};
/* clang-format on */
static WindowDesc _select_company_livery_desc(
WDP_AUTO, "company_color_scheme", 0, 0,
WC_COMPANY_COLOUR, WC_NONE,
{},
_nested_select_company_livery_widgets
);
static WindowDesc _select_company_livery_desc(WDP_AUTO, "company_color_scheme", 0, 0, WC_COMPANY_COLOUR, WC_NONE, {}, _nested_select_company_livery_widgets);
void ShowCompanyLiveryWindow(CompanyID company, GroupID group)
{
@ -1145,10 +1161,17 @@ void DrawCompanyManagerFace(CompanyManagerFace cmf, Colours colour, const Rect &
pal = PAL_NONE;
} else {
switch (GetCompanyManagerFaceBits(cmf, CMFV_EYE_COLOUR, ge)) {
default: NOT_REACHED();
case 0: pal = PALETTE_TO_BROWN; break;
case 1: pal = PALETTE_TO_BLUE; break;
case 2: pal = PALETTE_TO_GREEN; break;
default:
NOT_REACHED();
case 0:
pal = PALETTE_TO_BROWN;
break;
case 1:
pal = PALETTE_TO_BLUE;
break;
case 2:
pal = PALETTE_TO_GREEN;
break;
}
}
@ -1157,12 +1180,21 @@ void DrawCompanyManagerFace(CompanyManagerFace cmf, Colours colour, const Rect &
for (CompanyManagerFaceVariable cmfv = CMFV_CHEEKS; cmfv < CMFV_END; cmfv++) {
switch (cmfv) {
case CMFV_MOUSTACHE: if (!has_moustache) continue; break;
case CMFV_MOUSTACHE:
if (!has_moustache) continue;
break;
case CMFV_LIPS:
case CMFV_NOSE: if (has_moustache) continue; break;
case CMFV_TIE_EARRING: if (!has_tie_earring) continue; break;
case CMFV_GLASSES: if (!has_glasses) continue; break;
default: break;
case CMFV_NOSE:
if (has_moustache) continue;
break;
case CMFV_TIE_EARRING:
if (!has_tie_earring) continue;
break;
case CMFV_GLASSES:
if (!has_glasses) continue;
break;
default:
break;
}
DrawSprite(GetCompanyManagerFaceSprite(cmf, cmfv, ge), (cmfv == CMFV_EYEBROWS) ? pal : PAL_NONE, x, y);
}
@ -1328,8 +1360,7 @@ static constexpr NWidgetPart _nested_select_company_manager_face_widgets[] = {
/* clang-format on */
/** Management class for customizing the face of the company manager. */
class SelectCompanyManagerFaceWindow : public Window
{
class SelectCompanyManagerFaceWindow : public Window {
CompanyManagerFace face{}; ///< company manager face bits
bool advanced = false; ///< advanced company manager face selection window
@ -1479,51 +1510,42 @@ public:
this->SetWidgetLoweredState(WID_SCMF_ETHNICITY_EUR, !HasBit(this->ge, ETHNICITY_BLACK));
this->SetWidgetLoweredState(WID_SCMF_ETHNICITY_AFR, HasBit(this->ge, ETHNICITY_BLACK));
/* Disable dynamically the widgets which CompanyManagerFaceVariable has less than 2 options
* (or in other words you haven't any choice).
* If the widgets depend on a HAS-variable and this is false the widgets will be disabled, too. */
/* Eye colour buttons */
this->SetWidgetsDisabledState(_cmf_info[CMFV_EYE_COLOUR].valid_values[this->ge] < 2,
WID_SCMF_EYECOLOUR, WID_SCMF_EYECOLOUR_L, WID_SCMF_EYECOLOUR_R);
this->SetWidgetsDisabledState(_cmf_info[CMFV_EYE_COLOUR].valid_values[this->ge] < 2, WID_SCMF_EYECOLOUR, WID_SCMF_EYECOLOUR_L, WID_SCMF_EYECOLOUR_R);
/* Chin buttons */
this->SetWidgetsDisabledState(_cmf_info[CMFV_CHIN].valid_values[this->ge] < 2,
WID_SCMF_CHIN, WID_SCMF_CHIN_L, WID_SCMF_CHIN_R);
this->SetWidgetsDisabledState(_cmf_info[CMFV_CHIN].valid_values[this->ge] < 2, WID_SCMF_CHIN, WID_SCMF_CHIN_L, WID_SCMF_CHIN_R);
/* Eyebrows buttons */
this->SetWidgetsDisabledState(_cmf_info[CMFV_EYEBROWS].valid_values[this->ge] < 2,
WID_SCMF_EYEBROWS, WID_SCMF_EYEBROWS_L, WID_SCMF_EYEBROWS_R);
this->SetWidgetsDisabledState(_cmf_info[CMFV_EYEBROWS].valid_values[this->ge] < 2, WID_SCMF_EYEBROWS, WID_SCMF_EYEBROWS_L, WID_SCMF_EYEBROWS_R);
/* Lips or (if it a male face with a moustache) moustache buttons */
this->SetWidgetsDisabledState(_cmf_info[this->is_moust_male ? CMFV_MOUSTACHE : CMFV_LIPS].valid_values[this->ge] < 2,
WID_SCMF_LIPS_MOUSTACHE, WID_SCMF_LIPS_MOUSTACHE_L, WID_SCMF_LIPS_MOUSTACHE_R);
this->SetWidgetsDisabledState(
_cmf_info[this->is_moust_male ? CMFV_MOUSTACHE : CMFV_LIPS].valid_values[this->ge] < 2, WID_SCMF_LIPS_MOUSTACHE, WID_SCMF_LIPS_MOUSTACHE_L, WID_SCMF_LIPS_MOUSTACHE_R);
/* Nose buttons | male faces with moustache haven't any nose options */
this->SetWidgetsDisabledState(_cmf_info[CMFV_NOSE].valid_values[this->ge] < 2 || this->is_moust_male,
WID_SCMF_NOSE, WID_SCMF_NOSE_L, WID_SCMF_NOSE_R);
this->SetWidgetsDisabledState(_cmf_info[CMFV_NOSE].valid_values[this->ge] < 2 || this->is_moust_male, WID_SCMF_NOSE, WID_SCMF_NOSE_L, WID_SCMF_NOSE_R);
/* Hair buttons */
this->SetWidgetsDisabledState(_cmf_info[CMFV_HAIR].valid_values[this->ge] < 2,
WID_SCMF_HAIR, WID_SCMF_HAIR_L, WID_SCMF_HAIR_R);
this->SetWidgetsDisabledState(_cmf_info[CMFV_HAIR].valid_values[this->ge] < 2, WID_SCMF_HAIR, WID_SCMF_HAIR_L, WID_SCMF_HAIR_R);
/* Jacket buttons */
this->SetWidgetsDisabledState(_cmf_info[CMFV_JACKET].valid_values[this->ge] < 2,
WID_SCMF_JACKET, WID_SCMF_JACKET_L, WID_SCMF_JACKET_R);
this->SetWidgetsDisabledState(_cmf_info[CMFV_JACKET].valid_values[this->ge] < 2, WID_SCMF_JACKET, WID_SCMF_JACKET_L, WID_SCMF_JACKET_R);
/* Collar buttons */
this->SetWidgetsDisabledState(_cmf_info[CMFV_COLLAR].valid_values[this->ge] < 2,
WID_SCMF_COLLAR, WID_SCMF_COLLAR_L, WID_SCMF_COLLAR_R);
this->SetWidgetsDisabledState(_cmf_info[CMFV_COLLAR].valid_values[this->ge] < 2, WID_SCMF_COLLAR, WID_SCMF_COLLAR_L, WID_SCMF_COLLAR_R);
/* Tie/earring buttons | female faces without earring haven't any earring options */
this->SetWidgetsDisabledState(_cmf_info[CMFV_TIE_EARRING].valid_values[this->ge] < 2 ||
(this->is_female && GetCompanyManagerFaceBits(this->face, CMFV_HAS_TIE_EARRING, this->ge) == 0),
this->SetWidgetsDisabledState(_cmf_info[CMFV_TIE_EARRING].valid_values[this->ge] < 2 || (this->is_female && GetCompanyManagerFaceBits(this->face, CMFV_HAS_TIE_EARRING, this->ge) == 0),
WID_SCMF_TIE_EARRING, WID_SCMF_TIE_EARRING_L, WID_SCMF_TIE_EARRING_R);
/* Glasses buttons | faces without glasses haven't any glasses options */
this->SetWidgetsDisabledState(_cmf_info[CMFV_GLASSES].valid_values[this->ge] < 2 || GetCompanyManagerFaceBits(this->face, CMFV_HAS_GLASSES, this->ge) == 0,
WID_SCMF_GLASSES, WID_SCMF_GLASSES_L, WID_SCMF_GLASSES_R);
this->SetWidgetsDisabledState(
_cmf_info[CMFV_GLASSES].valid_values[this->ge] < 2 || GetCompanyManagerFaceBits(this->face, CMFV_HAS_GLASSES, this->ge) == 0, WID_SCMF_GLASSES, WID_SCMF_GLASSES_L, WID_SCMF_GLASSES_R);
this->DrawWidgets();
}
@ -1663,25 +1685,51 @@ public:
if (widget < WID_SCMF_EYECOLOUR_L) { // Bool buttons
switch (widget - WID_SCMF_HAS_MOUSTACHE_EARRING) {
default: NOT_REACHED();
case 0: cmfv = this->is_female ? CMFV_HAS_TIE_EARRING : CMFV_HAS_MOUSTACHE; break; // Has earring/moustache button
case 1: cmfv = CMFV_HAS_GLASSES; break; // Has glasses button
default:
NOT_REACHED();
case 0:
cmfv = this->is_female ? CMFV_HAS_TIE_EARRING : CMFV_HAS_MOUSTACHE;
break; // Has earring/moustache button
case 1:
cmfv = CMFV_HAS_GLASSES;
break; // Has glasses button
}
SetCompanyManagerFaceBits(this->face, cmfv, this->ge, !GetCompanyManagerFaceBits(this->face, cmfv, this->ge));
ScaleAllCompanyManagerFaceBits(this->face);
} else { // Value buttons
switch ((widget - WID_SCMF_EYECOLOUR_L) / 3) {
default: NOT_REACHED();
case 0: cmfv = CMFV_EYE_COLOUR; break; // Eye colour buttons
case 1: cmfv = CMFV_CHIN; break; // Chin buttons
case 2: cmfv = CMFV_EYEBROWS; break; // Eyebrows buttons
case 3: cmfv = this->is_moust_male ? CMFV_MOUSTACHE : CMFV_LIPS; break; // Moustache or lips buttons
case 4: cmfv = CMFV_NOSE; break; // Nose buttons
case 5: cmfv = CMFV_HAIR; break; // Hair buttons
case 6: cmfv = CMFV_JACKET; break; // Jacket buttons
case 7: cmfv = CMFV_COLLAR; break; // Collar buttons
case 8: cmfv = CMFV_TIE_EARRING; break; // Tie/earring buttons
case 9: cmfv = CMFV_GLASSES; break; // Glasses buttons
default:
NOT_REACHED();
case 0:
cmfv = CMFV_EYE_COLOUR;
break; // Eye colour buttons
case 1:
cmfv = CMFV_CHIN;
break; // Chin buttons
case 2:
cmfv = CMFV_EYEBROWS;
break; // Eyebrows buttons
case 3:
cmfv = this->is_moust_male ? CMFV_MOUSTACHE : CMFV_LIPS;
break; // Moustache or lips buttons
case 4:
cmfv = CMFV_NOSE;
break; // Nose buttons
case 5:
cmfv = CMFV_HAIR;
break; // Hair buttons
case 6:
cmfv = CMFV_JACKET;
break; // Jacket buttons
case 7:
cmfv = CMFV_COLLAR;
break; // Collar buttons
case 8:
cmfv = CMFV_TIE_EARRING;
break; // Tie/earring buttons
case 9:
cmfv = CMFV_GLASSES;
break; // Glasses buttons
}
/* 0 == left (_L), 1 == middle or 2 == right (_R) - button click */
IncreaseCompanyManagerFaceBits(this->face, cmfv, this->ge, (((widget - WID_SCMF_EYECOLOUR_L) % 3) != 0) ? 1 : -1);
@ -1710,12 +1758,7 @@ public:
};
/** Company manager face selection window description */
static WindowDesc _select_company_manager_face_desc(
WDP_AUTO, nullptr, 0, 0,
WC_COMPANY_MANAGER_FACE, WC_NONE,
WindowDefaultFlag::Construction,
_nested_select_company_manager_face_widgets
);
static WindowDesc _select_company_manager_face_desc(WDP_AUTO, nullptr, 0, 0, WC_COMPANY_MANAGER_FACE, WC_NONE, WindowDefaultFlag::Construction, _nested_select_company_manager_face_widgets);
/**
* Open the simple/advanced company manager face selection window
@ -1754,8 +1797,7 @@ static constexpr NWidgetPart _nested_company_infrastructure_widgets[] = {
/**
* Window with detailed information about the company's infrastructure.
*/
struct CompanyInfrastructureWindow : Window
{
struct CompanyInfrastructureWindow : Window {
enum class InfrastructureItemType : uint8_t {
Header, ///< Section header.
Spacer, ///< Spacer
@ -1941,7 +1983,8 @@ struct CompanyInfrastructureWindow : Window
this->count_width = GetStringBoundingBox(GetString(STR_JUST_COMMA, max_count)).width;
if (_settings_game.economy.infrastructure_maintenance) {
this->cost_width = GetStringBoundingBox(GetString(TimerGameEconomy::UsingWallclockUnits() ? STR_COMPANY_INFRASTRUCTURE_VIEW_TOTAL_PERIOD : STR_COMPANY_INFRASTRUCTURE_VIEW_TOTAL_YEAR, max_cost)).width;
this->cost_width =
GetStringBoundingBox(GetString(TimerGameEconomy::UsingWallclockUnits() ? STR_COMPANY_INFRASTRUCTURE_VIEW_TOTAL_PERIOD : STR_COMPANY_INFRASTRUCTURE_VIEW_TOTAL_YEAR, max_cost)).width;
} else {
this->cost_width = 0;
}
@ -1978,14 +2021,16 @@ struct CompanyInfrastructureWindow : Window
case InfrastructureItemType::Total:
/* Draw line in the spacer above the total. */
GfxFillRect(costr.Translate(0, -WidgetDimensions::scaled.vsep_normal).WithHeight(WidgetDimensions::scaled.fullbevel.top), PC_WHITE);
DrawString(costr, GetString(TimerGameEconomy::UsingWallclockUnits() ? STR_COMPANY_INFRASTRUCTURE_VIEW_TOTAL_PERIOD : STR_COMPANY_INFRASTRUCTURE_VIEW_TOTAL_YEAR, it->cost * 12), TC_BLACK, SA_RIGHT | SA_FORCE);
DrawString(costr, GetString(TimerGameEconomy::UsingWallclockUnits() ? STR_COMPANY_INFRASTRUCTURE_VIEW_TOTAL_PERIOD : STR_COMPANY_INFRASTRUCTURE_VIEW_TOTAL_YEAR, it->cost * 12),
TC_BLACK, SA_RIGHT | SA_FORCE);
break;
case InfrastructureItemType::Value:
DrawString(labelr.Indent(WidgetDimensions::scaled.hsep_indent, rtl), GetString(it->label), TC_WHITE);
DrawString(countr, GetString(STR_JUST_COMMA, it->count), TC_WHITE, SA_RIGHT | SA_FORCE);
if (_settings_game.economy.infrastructure_maintenance) {
DrawString(costr, GetString(TimerGameEconomy::UsingWallclockUnits() ? STR_COMPANY_INFRASTRUCTURE_VIEW_TOTAL_PERIOD : STR_COMPANY_INFRASTRUCTURE_VIEW_TOTAL_YEAR, it->cost * 12), TC_BLACK, SA_RIGHT | SA_FORCE);
DrawString(costr, GetString(TimerGameEconomy::UsingWallclockUnits() ? STR_COMPANY_INFRASTRUCTURE_VIEW_TOTAL_PERIOD : STR_COMPANY_INFRASTRUCTURE_VIEW_TOTAL_YEAR, it->cost * 12),
TC_BLACK, SA_RIGHT | SA_FORCE);
}
break;
}
@ -2019,12 +2064,7 @@ struct CompanyInfrastructureWindow : Window
}
};
static WindowDesc _company_infrastructure_desc(
WDP_AUTO, "company_infrastructure", 0, 0,
WC_COMPANY_INFRASTRUCTURE, WC_NONE,
{},
_nested_company_infrastructure_widgets
);
static WindowDesc _company_infrastructure_desc(WDP_AUTO, "company_infrastructure", 0, 0, WC_COMPANY_INFRASTRUCTURE, WC_NONE, {}, _nested_company_infrastructure_widgets);
/**
* Open the infrastructure window of a company.
@ -2115,15 +2155,12 @@ static constexpr NWidgetPart _nested_company_widgets[] = {
/* clang-format on */
/** Strings for the company vehicle counts */
static const StringID _company_view_vehicle_count_strings[] = {
STR_COMPANY_VIEW_TRAINS, STR_COMPANY_VIEW_ROAD_VEHICLES, STR_COMPANY_VIEW_SHIPS, STR_COMPANY_VIEW_AIRCRAFT
};
static const StringID _company_view_vehicle_count_strings[] = {STR_COMPANY_VIEW_TRAINS, STR_COMPANY_VIEW_ROAD_VEHICLES, STR_COMPANY_VIEW_SHIPS, STR_COMPANY_VIEW_AIRCRAFT};
/**
* Window with general information about a company
*/
struct CompanyWindow : Window
{
struct CompanyWindow : Window {
CompanyWidgets query_widget{};
/** Display planes in the company window. */
@ -2168,7 +2205,8 @@ struct CompanyWindow : Window
reinit |= this->GetWidget<NWidgetStacked>(WID_C_SELECT_HOSTILE_TAKEOVER)->SetDisplayedPlane((local || _local_company == COMPANY_SPECTATOR || !c->is_ai || _networking) ? SZSP_NONE : 0);
/* Multiplayer buttons. */
reinit |= this->GetWidget<NWidgetStacked>(WID_C_SELECT_MULTIPLAYER)->SetDisplayedPlane((!_networking || !NetworkCanJoinCompany(c->index) || _local_company == c->index) ? (int)SZSP_NONE : 0);
reinit |=
this->GetWidget<NWidgetStacked>(WID_C_SELECT_MULTIPLAYER)->SetDisplayedPlane((!_networking || !NetworkCanJoinCompany(c->index) || _local_company == c->index) ? (int)SZSP_NONE : 0);
this->SetWidgetDisabledState(WID_C_COMPANY_JOIN, c->is_ai);
@ -2360,7 +2398,9 @@ struct CompanyWindow : Window
void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
{
switch (widget) {
case WID_C_NEW_FACE: DoSelectCompanyManagerFace(this); break;
case WID_C_NEW_FACE:
DoSelectCompanyManagerFace(this);
break;
case WID_C_COLOUR_SCHEME:
ShowCompanyLiveryWindow(this->window_number, GroupID::Invalid());
@ -2368,12 +2408,14 @@ struct CompanyWindow : Window
case WID_C_PRESIDENT_NAME:
this->query_widget = WID_C_PRESIDENT_NAME;
ShowQueryString(GetString(STR_PRESIDENT_NAME, this->window_number), STR_COMPANY_VIEW_PRESIDENT_S_NAME_QUERY_CAPTION, MAX_LENGTH_PRESIDENT_NAME_CHARS, this, CS_ALPHANUMERAL, {QueryStringFlag::EnableDefault, QueryStringFlag::LengthIsInChars});
ShowQueryString(GetString(STR_PRESIDENT_NAME, this->window_number), STR_COMPANY_VIEW_PRESIDENT_S_NAME_QUERY_CAPTION, MAX_LENGTH_PRESIDENT_NAME_CHARS, this, CS_ALPHANUMERAL,
{QueryStringFlag::EnableDefault, QueryStringFlag::LengthIsInChars});
break;
case WID_C_COMPANY_NAME:
this->query_widget = WID_C_COMPANY_NAME;
ShowQueryString(GetString(STR_COMPANY_NAME, this->window_number), STR_COMPANY_VIEW_COMPANY_NAME_QUERY_CAPTION, MAX_LENGTH_COMPANY_NAME_CHARS, this, CS_ALPHANUMERAL, {QueryStringFlag::EnableDefault, QueryStringFlag::LengthIsInChars});
ShowQueryString(GetString(STR_COMPANY_NAME, this->window_number), STR_COMPANY_VIEW_COMPANY_NAME_QUERY_CAPTION, MAX_LENGTH_COMPANY_NAME_CHARS, this, CS_ALPHANUMERAL,
{QueryStringFlag::EnableDefault, QueryStringFlag::LengthIsInChars});
break;
case WID_C_VIEW_HQ: {
@ -2462,7 +2504,8 @@ struct CompanyWindow : Window
if (!str.has_value()) return;
switch (this->query_widget) {
default: NOT_REACHED();
default:
NOT_REACHED();
case WID_C_GIVE_MONEY: {
Money money = std::strtoull(str->c_str(), nullptr, 10) / GetCurrency().rate;
@ -2489,12 +2532,7 @@ struct CompanyWindow : Window
}
};
static WindowDesc _company_desc(
WDP_AUTO, "company", 0, 0,
WC_COMPANY, WC_NONE,
{},
_nested_company_widgets
);
static WindowDesc _company_desc(WDP_AUTO, "company", 0, 0, WC_COMPANY, WC_NONE, {}, _nested_company_widgets);
/**
* Show the window with the overview of the company.
@ -2622,12 +2660,7 @@ static constexpr NWidgetPart _nested_buy_company_widgets[] = {
};
/* clang-format on */
static WindowDesc _buy_company_desc(
WDP_AUTO, nullptr, 0, 0,
WC_BUY_COMPANY, WC_NONE,
WindowDefaultFlag::Construction,
_nested_buy_company_widgets
);
static WindowDesc _buy_company_desc(WDP_AUTO, nullptr, 0, 0, WC_BUY_COMPANY, WC_NONE, WindowDefaultFlag::Construction, _nested_buy_company_widgets);
/**
* Show the query to buy another company.

View File

@ -11,8 +11,8 @@
#define COMPANY_GUI_H
#include "company_type.h"
#include "group.h"
#include "gfx_type.h"
#include "group.h"
TextColour GetDrawStringCompanyColour(CompanyID company);
void DrawCompanyIcon(CompanyID c, int x, int y);

View File

@ -10,11 +10,12 @@
#ifndef COMPANY_MANAGER_FACE_H
#define COMPANY_MANAGER_FACE_H
#include "core/random_func.hpp"
#include "core/bitmath_func.hpp"
#include "table/sprites.h"
#include "core/random_func.hpp"
#include "company_type.h"
#include "table/sprites.h"
/** The gender/race combinations that we have faces for */
enum GenderEthnicity : uint8_t {
GENDER_FEMALE = 0, ///< This bit set means a female, otherwise male
@ -63,7 +64,8 @@ struct CompanyManagerFaceBitsInfo {
/** Lookup table for indices into the CompanyManagerFace, valid ranges and sprites */
static const CompanyManagerFaceBitsInfo _cmf_info[] = {
/* Index off len WM WF BM BF WM WF BM BF
* CMFV_GENDER */ { 0, 1, { 2, 2, 2, 2 }, { 0, 0, 0, 0 } }, ///< 0 = male, 1 = female
* CMFV_GENDER */
{0, 1, {2, 2, 2, 2}, {0, 0, 0, 0}}, ///< 0 = male, 1 = female
/* CMFV_ETHNICITY */ {1, 2, {2, 2, 2, 2}, {0, 0, 0, 0}}, ///< 0 = (Western-)Caucasian, 1 = African(-American)/Black
/* CMFV_GEN_ETHN */ {0, 3, {4, 4, 4, 4}, {0, 0, 0, 0}}, ///< Shortcut to get/set gender _and_ ethnicity
/* CMFV_HAS_MOUSTACHE */ {3, 1, {2, 0, 2, 0}, {0, 0, 0, 0}}, ///< Females do not have a moustache

View File

@ -43,7 +43,11 @@ typedef Owner CompanyID;
class CompanyMask : public BaseBitSet<CompanyMask, CompanyID, uint16_t> {
public:
constexpr CompanyMask() : BaseBitSet<CompanyMask, CompanyID, uint16_t>() {}
static constexpr size_t DecayValueType(CompanyID value) { return value.base(); }
static constexpr size_t DecayValueType(CompanyID value)
{
return value.base();
}
constexpr auto operator<=>(const CompanyMask &) const noexcept = default;
};

View File

@ -8,12 +8,13 @@
/** @file console.cpp Handling of the in-game console. */
#include "stdafx.h"
#include "console_internal.h"
#include "network/network.h"
#include "network/network_func.h"
#include "network/network_admin.h"
#include "debug.h"
#include "console_func.h"
#include "console_internal.h"
#include "debug.h"
#include "network/network.h"
#include "network/network_admin.h"
#include "network/network_func.h"
#include "settings_type.h"
#include "safeguards.h"
@ -384,8 +385,10 @@ void IConsoleCmdExec(const std::string &command_string, const uint recurse_count
}
return;
case CHR_DISALLOW: return;
case CHR_HIDE: break;
case CHR_DISALLOW:
return;
case CHR_HIDE:
break;
}
}

View File

@ -8,42 +8,44 @@
/** @file console_cmds.cpp Implementation of the console hooks. */
#include "stdafx.h"
#include "console_internal.h"
#include "debug.h"
#include "engine_func.h"
#include "landscape.h"
#include "saveload/saveload.h"
#include "3rdparty/fmt/chrono.h"
#include "network/core/network_game_info.h"
#include "network/network.h"
#include "network/network_func.h"
#include "network/network_base.h"
#include "network/network_admin.h"
#include "network/network_client.h"
#include "command_func.h"
#include "settings_func.h"
#include "fios.h"
#include "fileio_func.h"
#include "fontcache.h"
#include "screenshot.h"
#include "genworld.h"
#include "strings_func.h"
#include "viewport_func.h"
#include "window_func.h"
#include "timer/timer.h"
#include "company_func.h"
#include "gamelog.h"
#include "ai/ai.hpp"
#include "ai/ai_config.hpp"
#include "command_func.h"
#include "company_cmd.h"
#include "company_func.h"
#include "console_func.h"
#include "console_internal.h"
#include "debug.h"
#include "engine_base.h"
#include "engine_func.h"
#include "fileio_func.h"
#include "fios.h"
#include "fontcache.h"
#include "game/game.hpp"
#include "gamelog.h"
#include "genworld.h"
#include "landscape.h"
#include "misc_cmd.h"
#include "network/network.h"
#include "network/network_admin.h"
#include "network/network_base.h"
#include "network/network_client.h"
#include "network/network_func.h"
#include "newgrf.h"
#include "newgrf_profiling.h"
#include "console_func.h"
#include "engine_base.h"
#include "road.h"
#include "rail.h"
#include "game/game.hpp"
#include "3rdparty/fmt/chrono.h"
#include "company_cmd.h"
#include "misc_cmd.h"
#include "road.h"
#include "saveload/saveload.h"
#include "screenshot.h"
#include "settings_func.h"
#include "strings_func.h"
#include "timer/timer.h"
#include "viewport_func.h"
#include "window_func.h"
#include "table/strings.h"
@ -73,9 +75,7 @@ static IntervalTimer<TimerGameCalendar> _scheduled_monthly_timer = {{TimerGameCa
/** File list storage for the console, for caching the last 'ls' command. */
class ConsoleFileList : public FileList {
public:
ConsoleFileList(AbstractFileType abstract_filetype, bool show_dirs) : FileList(), abstract_filetype(abstract_filetype), show_dirs(show_dirs)
{
}
ConsoleFileList(AbstractFileType abstract_filetype, bool show_dirs) : FileList(), abstract_filetype(abstract_filetype), show_dirs(show_dirs) {}
/** Declare the file storage cache as being invalid, also clears all stored files. */
void InvalidateFileList()
@ -546,7 +546,6 @@ static bool ConRemove([[maybe_unused]] uint8_t argc, [[maybe_unused]] char *argv
return true;
}
/* List all the files in the current dir via console */
static bool ConListFiles([[maybe_unused]] uint8_t argc, [[maybe_unused]] char *argv[])
{
@ -615,7 +614,8 @@ static bool ConChangeDirectory([[maybe_unused]] uint8_t argc, [[maybe_unused]] c
case DFT_FIOS_PARENT:
FiosBrowseTo(item);
break;
default: IConsolePrint(CC_ERROR, "{}: Not a directory.", file);
default:
IConsolePrint(CC_ERROR, "{}: Not a directory.", file);
}
} else {
IConsolePrint(CC_ERROR, "{}: No such file or directory.", file);
@ -652,7 +652,6 @@ static bool ConClearBuffer([[maybe_unused]] uint8_t argc, [[maybe_unused]] char
return true;
}
/**********************************
* Network Core Console Commands
**********************************/
@ -1079,8 +1078,11 @@ static bool ConNetworkReconnect([[maybe_unused]] uint8_t argc, [[maybe_unused]]
CompanyID playas = (argc >= 2) ? (CompanyID)atoi(argv[1]) : COMPANY_SPECTATOR;
switch (playas.base()) {
case 0: playas = COMPANY_NEW_COMPANY; break;
case COMPANY_SPECTATOR.base(): /* nothing to do */ break;
case 0:
playas = COMPANY_NEW_COMPANY;
break;
case COMPANY_SPECTATOR.base(): /* nothing to do */
break;
default:
/* From a user pov 0 is a new company, internally it's different and all
* companies are offset by one to ease up on users (eg companies 1-8 not 0-7) */
@ -1745,7 +1747,9 @@ static bool ConDebugLevel([[maybe_unused]] uint8_t argc, [[maybe_unused]] char *
if (argc == 1) {
IConsolePrint(CC_DEFAULT, "Current debug-level: '{}'", GetDebugString());
} else {
SetDebugString(argv[1], [](const std::string &err) { IConsolePrint(CC_ERROR, err); });
SetDebugString(argv[1], [](const std::string &err) {
IConsolePrint(CC_ERROR, err);
});
}
return true;
@ -1867,14 +1871,9 @@ static bool ConCompanies([[maybe_unused]] uint8_t argc, [[maybe_unused]] char *a
std::string company_name = GetString(STR_COMPANY_NAME, c->index);
std::string colour = GetString(STR_COLOUR_DARK_BLUE + _company_colours[c->index]);
IConsolePrint(CC_INFO, "#:{}({}) Company Name: '{}' Year Founded: {} Money: {} Loan: {} Value: {} (T:{}, R:{}, P:{}, S:{}) {}",
c->index + 1, colour, company_name,
c->inaugurated_year, (int64_t)c->money, (int64_t)c->current_loan, (int64_t)CalculateCompanyValue(c),
c->group_all[VEH_TRAIN].num_vehicle,
c->group_all[VEH_ROAD].num_vehicle,
c->group_all[VEH_AIRCRAFT].num_vehicle,
c->group_all[VEH_SHIP].num_vehicle,
c->is_ai ? "AI" : "");
IConsolePrint(CC_INFO, "#:{}({}) Company Name: '{}' Year Founded: {} Money: {} Loan: {} Value: {} (T:{}, R:{}, P:{}, S:{}) {}", c->index + 1, colour, company_name, c->inaugurated_year,
(int64_t)c->money, (int64_t)c->current_loan, (int64_t)CalculateCompanyValue(c), c->group_all[VEH_TRAIN].num_vehicle, c->group_all[VEH_ROAD].num_vehicle,
c->group_all[VEH_AIRCRAFT].num_vehicle, c->group_all[VEH_SHIP].num_vehicle, c->is_ai ? "AI" : "");
}
return true;
@ -1958,7 +1957,8 @@ enum ConNetworkAuthorizedKeyAction : uint8_t {
CNAKA_REMOVE,
};
static void PerformNetworkAuthorizedKeyAction(std::string_view name, NetworkAuthorizedKeys *authorized_keys, ConNetworkAuthorizedKeyAction action, const std::string &authorized_key, CompanyID company = CompanyID::Invalid())
static void PerformNetworkAuthorizedKeyAction(
std::string_view name, NetworkAuthorizedKeys *authorized_keys, ConNetworkAuthorizedKeyAction action, const std::string &authorized_key, CompanyID company = CompanyID::Invalid())
{
switch (action) {
case CNAKA_LIST:
@ -2079,7 +2079,6 @@ static bool ConNetworkAuthorizedKey([[maybe_unused]] uint8_t argc, [[maybe_unuse
return false;
}
/* Content downloading only is available with ZLIB */
#if defined(WITH_ZLIB)
# include "network/network_content.h"
@ -2362,6 +2361,7 @@ static bool ConListDirs([[maybe_unused]] uint8_t argc, [[maybe_unused]] char *ar
const char *name; ///< UI name for the directory
bool default_only; ///< Whether only the default (first existing) directory for this is interesting
};
static const SubdirNameMap subdir_name_map[] = {
/* Game data directories */
{BASESET_DIR, "baseset", false},
@ -2467,7 +2467,9 @@ static bool ConNewGRFProfile([[maybe_unused]] uint8_t argc, [[maybe_unused]] cha
continue;
}
const GRFFile *grf = &files[grfnum - 1];
if (std::any_of(_newgrf_profilers.begin(), _newgrf_profilers.end(), [&](NewGRFProfiler &pr) { return pr.grffile == grf; })) {
if (std::any_of(_newgrf_profilers.begin(), _newgrf_profilers.end(), [&](NewGRFProfiler &pr) {
return pr.grffile == grf;
})) {
IConsolePrint(CC_WARNING, "GRF number {} [{:08X}] is already selected for profiling.", grfnum, std::byteswap(grf->grfid));
continue;
}
@ -2616,18 +2618,9 @@ static void ConDumpRoadTypes()
grfid = grf->grfid;
grfs.emplace(grfid, grf);
}
IConsolePrint(CC_DEFAULT, " {:02d} {} {}, Flags: {}{}{}{}{}, GRF: {:08X}, {}",
(uint)rt,
RoadTypeIsTram(rt) ? "Tram" : "Road",
FormatLabel(rti->label),
rti->flags.Test(RoadTypeFlag::Catenary) ? 'c' : '-',
rti->flags.Test(RoadTypeFlag::NoLevelCrossing) ? 'l' : '-',
rti->flags.Test(RoadTypeFlag::NoHouses) ? 'X' : '-',
rti->flags.Test(RoadTypeFlag::Hidden) ? 'h' : '-',
rti->flags.Test(RoadTypeFlag::TownBuild) ? 'T' : '-',
std::byteswap(grfid),
GetStringPtr(rti->strings.name)
);
IConsolePrint(CC_DEFAULT, " {:02d} {} {}, Flags: {}{}{}{}{}, GRF: {:08X}, {}", (uint)rt, RoadTypeIsTram(rt) ? "Tram" : "Road", FormatLabel(rti->label),
rti->flags.Test(RoadTypeFlag::Catenary) ? 'c' : '-', rti->flags.Test(RoadTypeFlag::NoLevelCrossing) ? 'l' : '-', rti->flags.Test(RoadTypeFlag::NoHouses) ? 'X' : '-',
rti->flags.Test(RoadTypeFlag::Hidden) ? 'h' : '-', rti->flags.Test(RoadTypeFlag::TownBuild) ? 'T' : '-', std::byteswap(grfid), GetStringPtr(rti->strings.name));
}
for (const auto &grf : grfs) {
IConsolePrint(CC_DEFAULT, " GRF: {:08X} = {}", std::byteswap(grf.first), grf.second->filename);
@ -2654,18 +2647,9 @@ static void ConDumpRailTypes()
grfid = grf->grfid;
grfs.emplace(grfid, grf);
}
IConsolePrint(CC_DEFAULT, " {:02d} {}, Flags: {}{}{}{}{}{}, GRF: {:08X}, {}",
(uint)rt,
FormatLabel(rti->label),
rti->flags.Test(RailTypeFlag::Catenary) ? 'c' : '-',
rti->flags.Test(RailTypeFlag::NoLevelCrossing) ? 'l' : '-',
rti->flags.Test(RailTypeFlag::Hidden) ? 'h' : '-',
rti->flags.Test(RailTypeFlag::NoSpriteCombine) ? 's' : '-',
rti->flags.Test(RailTypeFlag::Allow90Deg) ? 'a' : '-',
rti->flags.Test(RailTypeFlag::Disallow90Deg) ? 'd' : '-',
std::byteswap(grfid),
GetStringPtr(rti->strings.name)
);
IConsolePrint(CC_DEFAULT, " {:02d} {}, Flags: {}{}{}{}{}{}, GRF: {:08X}, {}", (uint)rt, FormatLabel(rti->label), rti->flags.Test(RailTypeFlag::Catenary) ? 'c' : '-',
rti->flags.Test(RailTypeFlag::NoLevelCrossing) ? 'l' : '-', rti->flags.Test(RailTypeFlag::Hidden) ? 'h' : '-', rti->flags.Test(RailTypeFlag::NoSpriteCombine) ? 's' : '-',
rti->flags.Test(RailTypeFlag::Allow90Deg) ? 'a' : '-', rti->flags.Test(RailTypeFlag::Disallow90Deg) ? 'd' : '-', std::byteswap(grfid), GetStringPtr(rti->strings.name));
}
for (const auto &grf : grfs) {
IConsolePrint(CC_DEFAULT, " GRF: {:08X} = {}", std::byteswap(grf.first), grf.second->filename);
@ -2700,30 +2684,13 @@ static void ConDumpCargoTypes()
grfid = grf->grfid;
grfs.emplace(grfid, grf);
}
IConsolePrint(CC_DEFAULT, " {:02d} Bit: {:2d}, Label: {}, Callback mask: 0x{:02X}, Cargo class: {}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}, GRF: {:08X}, {}",
spec->Index(),
spec->bitnum,
FormatLabel(spec->label.base()),
spec->callback_mask.base(),
spec->classes.Test(CargoClass::Passengers) ? 'p' : '-',
spec->classes.Test(CargoClass::Mail) ? 'm' : '-',
spec->classes.Test(CargoClass::Express) ? 'x' : '-',
spec->classes.Test(CargoClass::Armoured) ? 'a' : '-',
spec->classes.Test(CargoClass::Bulk) ? 'b' : '-',
spec->classes.Test(CargoClass::PieceGoods) ? 'g' : '-',
spec->classes.Test(CargoClass::Liquid) ? 'l' : '-',
spec->classes.Test(CargoClass::Refrigerated) ? 'r' : '-',
spec->classes.Test(CargoClass::Hazardous) ? 'h' : '-',
spec->classes.Test(CargoClass::Covered) ? 'c' : '-',
spec->classes.Test(CargoClass::Oversized) ? 'o' : '-',
spec->classes.Test(CargoClass::Powderized) ? 'd' : '-',
spec->classes.Test(CargoClass::NotPourable) ? 'n' : '-',
spec->classes.Test(CargoClass::Potable) ? 'e' : '-',
spec->classes.Test(CargoClass::NonPotable) ? 'i' : '-',
spec->classes.Test(CargoClass::Special) ? 'S' : '-',
std::byteswap(grfid),
GetStringPtr(spec->name)
);
IConsolePrint(CC_DEFAULT, " {:02d} Bit: {:2d}, Label: {}, Callback mask: 0x{:02X}, Cargo class: {}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}, GRF: {:08X}, {}", spec->Index(), spec->bitnum,
FormatLabel(spec->label.base()), spec->callback_mask.base(), spec->classes.Test(CargoClass::Passengers) ? 'p' : '-', spec->classes.Test(CargoClass::Mail) ? 'm' : '-',
spec->classes.Test(CargoClass::Express) ? 'x' : '-', spec->classes.Test(CargoClass::Armoured) ? 'a' : '-', spec->classes.Test(CargoClass::Bulk) ? 'b' : '-',
spec->classes.Test(CargoClass::PieceGoods) ? 'g' : '-', spec->classes.Test(CargoClass::Liquid) ? 'l' : '-', spec->classes.Test(CargoClass::Refrigerated) ? 'r' : '-',
spec->classes.Test(CargoClass::Hazardous) ? 'h' : '-', spec->classes.Test(CargoClass::Covered) ? 'c' : '-', spec->classes.Test(CargoClass::Oversized) ? 'o' : '-',
spec->classes.Test(CargoClass::Powderized) ? 'd' : '-', spec->classes.Test(CargoClass::NotPourable) ? 'n' : '-', spec->classes.Test(CargoClass::Potable) ? 'e' : '-',
spec->classes.Test(CargoClass::NonPotable) ? 'i' : '-', spec->classes.Test(CargoClass::Special) ? 'S' : '-', std::byteswap(grfid), GetStringPtr(spec->name));
}
for (const auto &grf : grfs) {
IConsolePrint(CC_DEFAULT, " GRF: {:08X} = {}", std::byteswap(grf.first), grf.second->filename);

Some files were not shown because too many files have changed in this diff Show More