OpenTTD Source 20260107-master-g88a467db19
company_cmd.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
10#include "stdafx.h"
11#include "company_base.h"
12#include "company_func.h"
13#include "company_gui.h"
14#include "core/backup_type.hpp"
15#include "town.h"
16#include "news_func.h"
17#include "command_func.h"
18#include "network/network.h"
22#include "ai/ai.hpp"
23#include "ai/ai_instance.hpp"
24#include "ai/ai_config.hpp"
26#include "window_func.h"
27#include "strings_func.h"
28#include "sound_func.h"
29#include "rail.h"
30#include "core/pool_func.hpp"
32#include "settings_func.h"
33#include "vehicle_base.h"
34#include "vehicle_func.h"
35#include "smallmap_gui.h"
36#include "game/game.hpp"
37#include "goal_base.h"
38#include "story_base.h"
39#include "company_cmd.h"
40#include "timer/timer.h"
43#include "timer/timer_window.h"
44
46
47#include "table/strings.h"
48#include "table/company_face.h"
49
50#include "safeguards.h"
51
53void UpdateObjectColours(const Company *c);
54
60
63
64
69Company::Company(CompanyID index, StringID name_1, bool is_ai) : CompanyPool::PoolItem<&_company_pool>(index)
70{
71 this->name_1 = name_1;
72 this->is_ai = is_ai;
73 this->terraform_limit = (uint32_t)_settings_game.construction.terraform_frame_burst << 16;
74 this->clear_limit = (uint32_t)_settings_game.construction.clear_frame_burst << 16;
75 this->tree_limit = (uint32_t)_settings_game.construction.tree_frame_burst << 16;
76 this->build_object_limit = (uint32_t)_settings_game.construction.build_object_frame_burst << 16;
77
78 InvalidateWindowData(WC_PERFORMANCE_DETAIL, 0, CompanyID::Invalid());
79}
80
83{
84 if (CleaningPool()) return;
85
87}
88
93void Company::PostDestructor(size_t index)
94{
99 /* If the currently shown error message has this company in it, then close it. */
101}
102
108{
109 if (this->max_loan == COMPANY_MAX_LOAN_DEFAULT) return _economy.max_loan;
110 return this->max_loan;
111}
112
119void SetLocalCompany(CompanyID new_company)
120{
121 /* company could also be COMPANY_SPECTATOR or OWNER_NONE */
122 assert(Company::IsValidID(new_company) || new_company == COMPANY_SPECTATOR || new_company == OWNER_NONE);
123
124 /* If actually changing to another company, several windows need closing */
125 bool switching_company = _local_company != new_company;
126
127 /* Delete the chat window, if you were team chatting. */
129
130 assert(IsLocalCompany());
131
132 _current_company = _local_company = new_company;
133
134 if (switching_company) {
136 /* Delete any construction windows... */
138 }
139
140 /* ... and redraw the whole screen. */
145 ResetVehicleColourMap();
146}
147
154{
155 if (!Company::IsValidID(company)) return GetColourGradient(COLOUR_WHITE, SHADE_NORMAL).ToTextColour();
156 return GetColourGradient(_company_colours[company], SHADE_NORMAL).ToTextColour();
157}
158
168
175void DrawCompanyIcon(CompanyID c, int x, int y)
176{
177 DrawSprite(SPR_COMPANY_ICON, GetCompanyPalette(c), x, y);
178}
179
187{
188 if (cmf.style >= GetNumCompanyManagerFaceStyles()) return false;
189
190 /* Test if each enabled part is valid. */
191 FaceVars vars = GetCompanyManagerFaceVars(cmf.style);
192 for (uint var : SetBitIterator(GetActiveFaceVars(cmf, vars))) {
193 if (!vars[var].IsValid(cmf)) return false;
194 }
195
196 return true;
197}
198
200
207{
208 CompanyID cid = company->index;
210}
211
215static const IntervalTimer<TimerWindow> invalidate_company_windows_interval(std::chrono::milliseconds(1), [](auto) {
219 if (w != nullptr) {
225 }
227 }
229});
230
239{
240 if (_settings_game.difficulty.infinite_money) return INT64_MAX;
241 if (!Company::IsValidID(company)) return INT64_MAX;
242 return Company::Get(company)->money;
243}
244
256
264{
265 if (cost.GetCost() <= 0) return true;
267
269 if (c != nullptr && cost.GetCost() > c->money) {
270 cost.MakeError(STR_ERROR_NOT_ENOUGH_CASH_REQUIRES_CURRENCY);
271 if (IsLocalCompany()) {
272 cost.SetEncodedMessage(GetEncodedString(STR_ERROR_NOT_ENOUGH_CASH_REQUIRES_CURRENCY, cost.GetCost()));
273 }
274 return false;
275 }
276 return true;
277}
278
284static void SubtractMoneyFromCompany(Company *c, const CommandCost &cost)
285{
286 if (cost.GetCost() == 0) return;
287 assert(cost.GetExpensesType() != INVALID_EXPENSES);
288
289 c->money -= cost.GetCost();
290 c->yearly_expenses[0][cost.GetExpensesType()] += cost.GetCost();
291
296 c->cur_economy.income -= cost.GetCost();
297 } else if (HasBit(1 << EXPENSES_TRAIN_RUN |
300 1 << EXPENSES_SHIP_RUN |
301 1 << EXPENSES_PROPERTY |
303 c->cur_economy.expenses -= cost.GetCost();
304 }
305
307}
308
315{
316 Company *c = Company::GetIfValid(company);
317 if (c != nullptr) SubtractMoneyFromCompany(c, cost);
318}
319
326{
327 Company *c = Company::Get(company);
328 uint8_t m = c->money_fraction;
329 Money cost = cst.GetCost();
330
331 c->money_fraction = m - (uint8_t)cost;
332 cost >>= 8;
333 if (c->money_fraction > m) cost++;
334 if (cost != 0) SubtractMoneyFromCompany(c, CommandCost(cst.GetExpensesType(), cost));
335}
336
337static constexpr void UpdateLandscapingLimit(uint32_t &limit, uint64_t per_64k_frames, uint64_t burst)
338{
339 limit = static_cast<uint32_t>(std::min<uint64_t>(limit + per_64k_frames, burst << 16));
340}
341
352
359std::array<StringParameter, 2> GetParamsForOwnedBy(Owner owner, TileIndex tile)
360{
361 if (owner == OWNER_TOWN) {
362 assert(tile != 0);
363 const Town *t = ClosestTownFromTile(tile, UINT_MAX);
364 return {STR_TOWN_NAME, t->index};
365 }
366
367 if (!Company::IsValidID(owner)) {
368 return {STR_COMPANY_SOMEONE, std::monostate{}};
369 }
370
371 return {STR_COMPANY_NAME, owner};
372}
373
383{
384 assert(owner < OWNER_END);
385 assert(owner != OWNER_TOWN || tile != 0);
386
387 if (owner == _current_company) return CommandCost();
388
389 CommandCost error{STR_ERROR_OWNED_BY};
390 if (IsLocalCompany()) {
391 auto params = GetParamsForOwnedBy(owner, tile);
392 error.SetEncodedMessage(GetEncodedStringWithArgs(STR_ERROR_OWNED_BY, params));
393 if (owner != OWNER_TOWN) error.SetErrorOwner(owner);
394 }
395 return error;
396}
397
406{
407 return CheckOwnership(GetTileOwner(tile), tile);
408}
409
415{
416 if (c->name_1 != STR_SV_UNNAMED) return;
417 if (c->last_build_coordinate == 0) return;
418
420
421 StringID str;
422 uint32_t strp;
423 std::string name;
424 if (t->name.empty() && IsInsideMM(t->townnametype, SPECSTR_TOWNNAME_START, SPECSTR_TOWNNAME_END)) {
425 str = t->townnametype - SPECSTR_TOWNNAME_START + SPECSTR_COMPANY_NAME_START;
426 strp = t->townnameparts;
427
428verify_name:;
429 /* No companies must have this name already */
430 for (const Company *cc : Company::Iterate()) {
431 if (cc->name_1 == str && cc->name_2 == strp) goto bad_town_name;
432 }
433
434 name = GetString(str, strp);
435 if (Utf8StringLength(name) >= MAX_LENGTH_COMPANY_NAME_CHARS) goto bad_town_name;
436
437set_name:;
438 c->name_1 = str;
439 c->name_2 = strp;
440
442 AI::BroadcastNewEvent(new ScriptEventCompanyRenamed(c->index, name));
443 Game::NewEvent(new ScriptEventCompanyRenamed(c->index, name));
444
445 if (c->is_ai) {
446 auto cni = std::make_unique<CompanyNewsInformation>(STR_NEWS_COMPANY_LAUNCH_TITLE, c);
447 EncodedString headline = GetEncodedString(STR_NEWS_COMPANY_LAUNCH_DESCRIPTION, cni->company_name, t->index);
448 AddNewsItem(std::move(headline),
450 }
451 return;
452 }
453bad_town_name:;
454
456 str = SPECSTR_ANDCO_NAME;
457 strp = c->president_name_2;
458 name = GetString(str, strp);
459 goto set_name;
460 } else {
461 str = SPECSTR_ANDCO_NAME;
462 strp = Random();
463 goto verify_name;
464 }
465}
466
468static const uint8_t _colour_sort[COLOUR_END] = {2, 2, 3, 2, 3, 2, 3, 2, 3, 2, 2, 2, 3, 1, 1, 1};
470static const Colours _similar_colour[COLOUR_END][2] = {
471 { COLOUR_BLUE, COLOUR_LIGHT_BLUE }, // COLOUR_DARK_BLUE
472 { COLOUR_GREEN, COLOUR_DARK_GREEN }, // COLOUR_PALE_GREEN
473 { INVALID_COLOUR, INVALID_COLOUR }, // COLOUR_PINK
474 { COLOUR_ORANGE, INVALID_COLOUR }, // COLOUR_YELLOW
475 { INVALID_COLOUR, INVALID_COLOUR }, // COLOUR_RED
476 { COLOUR_DARK_BLUE, COLOUR_BLUE }, // COLOUR_LIGHT_BLUE
477 { COLOUR_PALE_GREEN, COLOUR_DARK_GREEN }, // COLOUR_GREEN
478 { COLOUR_PALE_GREEN, COLOUR_GREEN }, // COLOUR_DARK_GREEN
479 { COLOUR_DARK_BLUE, COLOUR_LIGHT_BLUE }, // COLOUR_BLUE
480 { COLOUR_BROWN, COLOUR_ORANGE }, // COLOUR_CREAM
481 { COLOUR_PURPLE, INVALID_COLOUR }, // COLOUR_MAUVE
482 { COLOUR_MAUVE, INVALID_COLOUR }, // COLOUR_PURPLE
483 { COLOUR_YELLOW, COLOUR_CREAM }, // COLOUR_ORANGE
484 { COLOUR_CREAM, INVALID_COLOUR }, // COLOUR_BROWN
485 { COLOUR_WHITE, INVALID_COLOUR }, // COLOUR_GREY
486 { COLOUR_GREY, INVALID_COLOUR }, // COLOUR_WHITE
487};
488
493static Colours GenerateCompanyColour()
494{
495 Colours colours[COLOUR_END];
496
497 /* Initialize array */
498 for (uint i = 0; i < COLOUR_END; i++) colours[i] = static_cast<Colours>(i);
499
500 /* And randomize it */
501 for (uint i = 0; i < 100; i++) {
502 uint r = Random();
503 std::swap(colours[GB(r, 0, 4)], colours[GB(r, 4, 4)]);
504 }
505
506 /* Bubble sort it according to the values in table 1 */
507 for (uint i = 0; i < COLOUR_END; i++) {
508 for (uint j = 1; j < COLOUR_END; j++) {
509 if (_colour_sort[colours[j - 1]] < _colour_sort[colours[j]]) {
510 std::swap(colours[j - 1], colours[j]);
511 }
512 }
513 }
514
515 /* Move the colours that look similar to each company's colour to the side */
516 for (const Company *c : Company::Iterate()) {
517 Colours pcolour = c->colour;
518
519 for (uint i = 0; i < COLOUR_END; i++) {
520 if (colours[i] == pcolour) {
521 colours[i] = INVALID_COLOUR;
522 break;
523 }
524 }
525
526 for (uint j = 0; j < 2; j++) {
527 Colours similar = _similar_colour[pcolour][j];
528 if (similar == INVALID_COLOUR) break;
529
530 for (uint i = 1; i < COLOUR_END; i++) {
531 if (colours[i - 1] == similar) std::swap(colours[i - 1], colours[i]);
532 }
533 }
534 }
535
536 /* Return the first available colour */
537 for (uint i = 0; i < COLOUR_END; i++) {
538 if (colours[i] != INVALID_COLOUR) return colours[i];
539 }
540
541 NOT_REACHED();
542}
543
549{
550 for (;;) {
551restart:;
554
555 /* Reserve space for extra unicode character. We need to do this to be able
556 * to detect too long president name. */
557 std::string name = GetString(STR_PRESIDENT_NAME, c->index);
559
560 for (const Company *cc : Company::Iterate()) {
561 if (c != cc) {
562 std::string other_name = GetString(STR_PRESIDENT_NAME, cc->index);
563 if (name == other_name) goto restart;
564 }
565 }
566 return;
567 }
568}
569
576{
577 for (LiveryScheme scheme = LS_BEGIN; scheme < LS_END; scheme++) {
578 c->livery[scheme].in_use.Reset();
579 c->livery[scheme].colour1 = c->colour;
580 c->livery[scheme].colour2 = c->colour;
581 }
582
583 for (Group *g : Group::Iterate()) {
584 if (g->owner == c->index) {
585 g->livery.in_use.Reset();
586 g->livery.colour1 = c->colour;
587 g->livery.colour2 = c->colour;
588 }
589 }
590}
591
599Company *DoStartupNewCompany(bool is_ai, CompanyID company = CompanyID::Invalid())
600{
601 if (!Company::CanAllocateItem()) return nullptr;
602
603 /* we have to generate colour before this company is valid */
604 Colours colour = GenerateCompanyColour();
605
606 Company *c;
607 if (company == CompanyID::Invalid()) {
608 c = Company::Create(STR_SV_UNNAMED, is_ai);
609 } else {
610 if (Company::IsValidID(company)) return nullptr;
611 c = Company::CreateAtIndex(company, STR_SV_UNNAMED, is_ai);
612 }
613
614 c->colour = colour;
615
618
619 /* Scale the initial loan based on the inflation rounded down to the loan interval. The maximum loan has already been inflation adjusted. */
620 c->money = c->current_loan = std::min<int64_t>((INITIAL_LOAN * _economy.inflation_prices >> 16) / LOAN_INTERVAL * LOAN_INTERVAL, _economy.max_loan);
621
626
627 /* If starting a player company in singleplayer and a favourite company manager face is selected, choose it. Otherwise, use a random face.
628 * In a network game, we'll choose the favourite face later in CmdCompanyCtrl to sync it to all clients. */
629 bool randomise_face = true;
630 if (!_company_manager_face.empty() && !is_ai && !_networking) {
632 if (cmf.has_value()) {
633 randomise_face = false;
634 c->face = std::move(*cmf);
635 }
636 }
637 if (randomise_face) RandomiseCompanyManagerFace(c->face, _random);
638
641
643
649
650 if (is_ai && (!_networking || _network_server)) AI::StartNew(c->index);
651
652 AI::BroadcastNewEvent(new ScriptEventCompanyNew(c->index), c->index);
653 Game::NewEvent(new ScriptEventCompanyNew(c->index));
654
655 return c;
656}
657
659TimeoutTimer<TimerGameTick> _new_competitor_timeout({ TimerGameTick::Priority::COMPETITOR_TIMEOUT, 0 }, []() {
660 if (_game_mode == GM_MENU || !AI::CanStartNew()) return;
663
664 /* count number of competitors */
665 uint8_t n = 0;
666 for (const Company *c : Company::Iterate()) {
667 if (c->is_ai) n++;
668 }
669
671
672 /* Send a command to all clients to start up a new AI.
673 * Works fine for Multiplayer and Singleplayer */
675});
676
679{
680 /* Ensure the timeout is aborted, so it doesn't fire based on information of the last game. */
682}
683
689
697{
698 const Company *c1 = Company::Get(cbig);
699 const Company *c2 = Company::Get(csmall);
700
701 /* Do the combined vehicle counts stay within the limits? */
702 return c1->group_all[VEH_TRAIN].num_vehicle + c2->group_all[VEH_TRAIN].num_vehicle <= _settings_game.vehicle.max_trains &&
703 c1->group_all[VEH_ROAD].num_vehicle + c2->group_all[VEH_ROAD].num_vehicle <= _settings_game.vehicle.max_roadveh &&
704 c1->group_all[VEH_SHIP].num_vehicle + c2->group_all[VEH_SHIP].num_vehicle <= _settings_game.vehicle.max_ships &&
705 c1->group_all[VEH_AIRCRAFT].num_vehicle + c2->group_all[VEH_AIRCRAFT].num_vehicle <= _settings_game.vehicle.max_aircraft;
706}
707
718{
719 /* Amount of time out for each company to take over a company;
720 * Timeout is a quarter (3 months of 30 days) divided over the
721 * number of companies. The minimum number of days in a quarter
722 * is 90: 31 in January, 28 in February and 31 in March.
723 * Note that the company going bankrupt can't buy itself. */
724 static const int TAKE_OVER_TIMEOUT = 3 * 30 * Ticks::DAY_TICKS / (MAX_COMPANIES - 1);
725
726 assert(c->bankrupt_asked.Any());
727
728 /* We're currently asking some company to buy 'us' */
729 if (c->bankrupt_timeout != 0) {
730 c->bankrupt_timeout -= MAX_COMPANIES;
731 if (c->bankrupt_timeout > 0) return;
732 c->bankrupt_timeout = 0;
733
734 return;
735 }
736
737 /* Did we ask everyone for bankruptcy? If so, bail out. */
738 if (c->bankrupt_asked.All()) return;
739
740 Company *best = nullptr;
741 int32_t best_performance = -1;
742
743 /* Ask the company with the highest performance history first */
744 for (Company *c2 : Company::Iterate()) {
745 if (c2->bankrupt_asked.None() && // Don't ask companies going bankrupt themselves
746 !c->bankrupt_asked.Test(c2->index) &&
747 best_performance < c2->old_economy[1].performance_history &&
748 CheckTakeoverVehicleLimit(c2->index, c->index)) {
749 best_performance = c2->old_economy[1].performance_history;
750 best = c2;
751 }
752 }
753
754 /* Asked all companies? */
755 if (best_performance == -1) {
756 c->bankrupt_asked.Set();
757 return;
758 }
759
760 c->bankrupt_asked.Set(best->index);
761
762 c->bankrupt_timeout = TAKE_OVER_TIMEOUT;
763
764 AI::NewEvent(best->index, new ScriptEventCompanyAskMerger(c->index, c->bankrupt_value));
765 if (IsInteractiveCompany(best->index)) {
766 ShowBuyCompanyDialog(c->index, false);
767 }
768}
769
772{
773 if (_game_mode == GM_EDITOR) return;
774
776 if (c != nullptr) {
777 if (c->name_1 != 0) GenerateCompanyName(c);
779 }
780
781 if (_new_competitor_timeout.HasFired() && _game_mode != GM_MENU && AI::CanStartNew()) {
783 /* If the interval is zero, start as many competitors as needed then check every ~10 minutes if a company went bankrupt and needs replacing. */
784 if (timeout == 0) {
785 /* count number of competitors */
786 uint8_t num_ais = 0;
787 for (const Company *cc : Company::Iterate()) {
788 if (cc->is_ai) num_ais++;
789 }
790
791 size_t num_companies = Company::GetNumItems();
792 for (auto i = 0; i < _settings_game.difficulty.max_no_competitors; i++) {
793 if (_networking && num_companies++ >= _settings_client.network.max_companies) break;
794 if (num_ais++ >= _settings_game.difficulty.max_no_competitors) break;
796 }
797 timeout = 10 * 60 * Ticks::TICKS_PER_SECOND;
798 }
799 /* Randomize a bit when the AI is actually going to start; ranges from 87.5% .. 112.5% of indicated value. */
800 timeout += ScriptObject::GetRandomizer(OWNER_NONE).Next(timeout / 4) - timeout / 8;
801
802 _new_competitor_timeout.Reset({ TimerGameTick::Priority::COMPETITOR_TIMEOUT, static_cast<uint>(std::max(1, timeout)) });
803 }
804
805 _cur_company_tick_index = (_cur_company_tick_index + 1) % MAX_COMPANIES;
806}
807
812static const IntervalTimer<TimerGameEconomy> _economy_companies_yearly({TimerGameEconomy::YEAR, TimerGameEconomy::Priority::COMPANY}, [](auto)
813{
814 /* Copy statistics */
815 for (Company *c : Company::Iterate()) {
816 /* Move expenses to previous years. */
817 std::rotate(std::rbegin(c->yearly_expenses), std::rbegin(c->yearly_expenses) + 1, std::rend(c->yearly_expenses));
818 c->yearly_expenses[0].fill(0);
820 }
821
825 if (c->num_valid_stat_ent > 5 && c->old_economy[0].performance_history < c->old_economy[4].performance_history) {
827 } else {
829 }
830 }
831});
832
839{
840 this->company_name = GetString(STR_COMPANY_NAME, c->index);
841
842 if (other != nullptr) {
843 this->other_company_name = GetString(STR_COMPANY_NAME, other->index);
844 c = other;
845 }
846
847 this->president_name = GetString(STR_PRESIDENT_NAME_MANAGER, c->index);
848
849 this->title = title;
850 this->colour = c->colour;
851 this->face = c->face;
852
853}
854
859void CompanyAdminUpdate(const Company *company)
860{
862}
863
873
883{
885
886 switch (cca) {
887 case CCA_NEW: { // Create a new company
888 /* This command is only executed in a multiplayer game */
889 if (!_networking) return CMD_ERROR;
890
891 /* Has the network client a correct ClientID? */
892 if (!flags.Test(DoCommandFlag::Execute)) return CommandCost();
893
895
896 /* Delete multiplayer progress bar */
898
899 Company *c = DoStartupNewCompany(false);
900
901 /* A new company could not be created, revert to being a spectator */
902 if (c == nullptr) {
903 /* We check for "ci != nullptr" as a client could have left by
904 * the time we execute this command. */
905 if (_network_server && ci != nullptr) {
908 }
909 break;
910 }
911
914
915 /* This is the client (or non-dedicated server) who wants a new company */
916 if (client_id == _network_own_client_id) {
919
920 /*
921 * If a favourite company manager face is selected, choose it. Otherwise, use a random face.
922 * Because this needs to be synchronised over the network, only the client knows
923 * its configuration and we are currently in the execution of a command, we have
924 * to circumvent the normal ::Post logic for commands and just send the command.
925 */
926 if (!_company_manager_face.empty()) {
928 if (cmf.has_value()) {
929 Command<CMD_SET_COMPANY_MANAGER_FACE>::SendNet(STR_NULL, c->index, cmf->style, cmf->bits);
930 }
931 }
932
933 /* Now that we have a new company, broadcast our company settings to
934 * all clients so everything is in sync */
936
938 }
939 break;
940 }
941
942 case CCA_NEW_AI: { // Make a new AI company
943 if (company_id != CompanyID::Invalid() && company_id >= MAX_COMPANIES) return CMD_ERROR;
944
945 /* For network games, company deletion is delayed. */
946 if (!_networking && company_id != CompanyID::Invalid() && Company::IsValidID(company_id)) return CMD_ERROR;
947
948 if (!flags.Test(DoCommandFlag::Execute)) return CommandCost();
949
950 /* For network game, just assume deletion happened. */
951 assert(company_id == CompanyID::Invalid() || !Company::IsValidID(company_id));
952
953 Company *c = DoStartupNewCompany(true, company_id);
954 if (c != nullptr) {
956 NetworkServerNewCompany(c, nullptr);
957 }
958 break;
959 }
960
961 case CCA_DELETE: { // Delete a company
962 if (reason >= CRR_END) return CMD_ERROR;
963
964 /* We can't delete the last existing company in singleplayer mode. */
965 if (!_networking && Company::GetNumItems() == 1) return CMD_ERROR;
966
967 Company *c = Company::GetIfValid(company_id);
968 if (c == nullptr) return CMD_ERROR;
969
970 if (!flags.Test(DoCommandFlag::Execute)) return CommandCost();
971
972 /* Show the bankrupt news */
973 auto cni = std::make_unique<CompanyNewsInformation>(STR_NEWS_COMPANY_BANKRUPT_TITLE, c);
974 EncodedString headline = GetEncodedString(STR_NEWS_COMPANY_BANKRUPT_DESCRIPTION, cni->company_name);
975 AddCompanyNewsItem(std::move(headline), std::move(cni));
976
977 /* Remove the company */
979 if (c->is_ai) AI::Stop(c->index);
980
981 CompanyID c_index = c->index;
982 delete c;
983 AI::BroadcastNewEvent(new ScriptEventCompanyBankrupt(c_index));
984 Game::NewEvent(new ScriptEventCompanyBankrupt(c_index));
985 CompanyAdminRemove(c_index, (CompanyRemoveReason)reason);
986
989
990 break;
991 }
992
993 default: return CMD_ERROR;
994 }
995
999
1000 return CommandCost();
1001}
1002
1003static bool ExecuteAllowListCtrlAction(CompanyAllowListCtrlAction action, Company *c, const std::string &public_key)
1004{
1005 switch (action) {
1006 case CALCA_ADD:
1007 return c->allow_list.Add(public_key);
1008
1009 case CALCA_REMOVE:
1010 return c->allow_list.Remove(public_key);
1011
1012 default:
1013 NOT_REACHED();
1014 }
1015}
1016
1025{
1027 if (c == nullptr) return CMD_ERROR;
1028
1029 /* The public key length includes the '\0'. */
1030 if (public_key.size() != NETWORK_PUBLIC_KEY_LENGTH - 1) return CMD_ERROR;
1031
1032 switch (action) {
1033 case CALCA_ADD:
1034 case CALCA_REMOVE:
1035 break;
1036
1037 default:
1038 return CMD_ERROR;
1039 }
1040
1041 if (flags.Test(DoCommandFlag::Execute)) {
1042 if (ExecuteAllowListCtrlAction(action, c, public_key)) {
1045 }
1046 }
1047
1048 return CommandCost();
1049}
1050
1058CommandCost CmdSetCompanyManagerFace(DoCommandFlags flags, uint style, uint32_t bits)
1059{
1060 CompanyManagerFace tmp_face{style, bits, {}};
1061 if (!IsValidCompanyManagerFace(tmp_face)) return CMD_ERROR;
1062
1063 if (flags.Test(DoCommandFlag::Execute)) {
1065 SetCompanyManagerFaceStyle(cmf, style);
1066 cmf.bits = tmp_face.bits;
1067
1069 }
1070 return CommandCost();
1071}
1072
1079{
1080 for (int i = 1; i < LS_END; i++) {
1081 if (!c->livery[i].in_use.Test(Livery::Flag::Primary)) c->livery[i].colour1 = c->livery[LS_DEFAULT].colour1;
1082 if (!c->livery[i].in_use.Test(Livery::Flag::Secondary)) c->livery[i].colour2 = c->livery[LS_DEFAULT].colour2;
1083 }
1085}
1086
1095CommandCost CmdSetCompanyColour(DoCommandFlags flags, LiveryScheme scheme, bool primary, Colours colour)
1096{
1097 if (scheme >= LS_END || (colour >= COLOUR_END && colour != INVALID_COLOUR)) return CMD_ERROR;
1098
1099 /* Default scheme can't be reset to invalid. */
1100 if (scheme == LS_DEFAULT && colour == INVALID_COLOUR) return CMD_ERROR;
1101
1103
1104 /* Ensure no two companies have the same primary colour */
1105 if (scheme == LS_DEFAULT && primary) {
1106 for (const Company *cc : Company::Iterate()) {
1107 if (cc != c && cc->colour == colour) return CMD_ERROR;
1108 }
1109 }
1110
1111 if (flags.Test(DoCommandFlag::Execute)) {
1112 if (primary) {
1113 if (scheme != LS_DEFAULT) c->livery[scheme].in_use.Set(Livery::Flag::Primary, colour != INVALID_COLOUR);
1114 if (colour == INVALID_COLOUR) colour = c->livery[LS_DEFAULT].colour1;
1115 c->livery[scheme].colour1 = colour;
1116
1117 /* If setting the first colour of the default scheme, adjust the
1118 * original and cached company colours too. */
1119 if (scheme == LS_DEFAULT) {
1122 c->colour = colour;
1124 }
1125 } else {
1126 if (scheme != LS_DEFAULT) c->livery[scheme].in_use.Set(Livery::Flag::Secondary, colour != INVALID_COLOUR);
1127 if (colour == INVALID_COLOUR) colour = c->livery[LS_DEFAULT].colour2;
1128 c->livery[scheme].colour2 = colour;
1129
1130 if (scheme == LS_DEFAULT) {
1132 }
1133 }
1134
1135 if (c->livery[scheme].in_use.Any({Livery::Flag::Primary, Livery::Flag::Secondary})) {
1136 /* If enabling a scheme, set the default scheme to be in use too */
1137 c->livery[LS_DEFAULT].in_use.Set(Livery::Flag::Primary);
1138 } else {
1139 /* Else loop through all schemes to see if any are left enabled.
1140 * If not, disable the default scheme too. */
1141 c->livery[LS_DEFAULT].in_use.Reset({Livery::Flag::Primary, Livery::Flag::Secondary});
1142 for (scheme = LS_DEFAULT; scheme < LS_END; scheme++) {
1143 if (c->livery[scheme].in_use.Any({Livery::Flag::Primary, Livery::Flag::Secondary})) {
1144 c->livery[LS_DEFAULT].in_use.Set(Livery::Flag::Primary);
1145 break;
1146 }
1147 }
1148 }
1149
1150 ResetVehicleColourMap();
1152
1153 /* All graph related to companies use the company colour. */
1160 /* The smallmap owner view also stores the company colours. */
1163
1164 /* Company colour data is indirectly cached. */
1165 for (Vehicle *v : Vehicle::Iterate()) {
1166 if (v->owner == _current_company) v->InvalidateNewGRFCache();
1167 }
1168
1170 }
1171 return CommandCost();
1172}
1173
1179static bool IsUniqueCompanyName(const std::string &name)
1180{
1181 for (const Company *c : Company::Iterate()) {
1182 if (!c->name.empty() && c->name == name) return false;
1183 }
1184
1185 return true;
1186}
1187
1194CommandCost CmdRenameCompany(DoCommandFlags flags, const std::string &text)
1195{
1196 bool reset = text.empty();
1197
1198 if (!reset) {
1200 if (!IsUniqueCompanyName(text)) return CommandCost(STR_ERROR_NAME_MUST_BE_UNIQUE);
1201 }
1202
1203 if (flags.Test(DoCommandFlag::Execute)) {
1205 if (reset) {
1206 c->name.clear();
1207 } else {
1208 c->name = text;
1209 }
1210
1214
1215 std::string new_name = GetString(STR_COMPANY_NAME, c->index);
1216 AI::BroadcastNewEvent(new ScriptEventCompanyRenamed(c->index, new_name));
1217 Game::NewEvent(new ScriptEventCompanyRenamed(c->index, new_name));
1218 }
1219
1220 return CommandCost();
1221}
1222
1228static bool IsUniquePresidentName(const std::string &name)
1229{
1230 for (const Company *c : Company::Iterate()) {
1231 if (!c->president_name.empty() && c->president_name == name) return false;
1232 }
1233
1234 return true;
1235}
1236
1243CommandCost CmdRenamePresident(DoCommandFlags flags, const std::string &text)
1244{
1245 bool reset = text.empty();
1246
1247 if (!reset) {
1249 if (!IsUniquePresidentName(text)) return CommandCost(STR_ERROR_NAME_MUST_BE_UNIQUE);
1250 }
1251
1252 if (flags.Test(DoCommandFlag::Execute)) {
1254
1255 if (reset) {
1256 c->president_name.clear();
1257 } else {
1258 c->president_name = text;
1259
1260 if (c->name_1 == STR_SV_UNNAMED && c->name.empty()) {
1262 }
1263 }
1264
1268
1269 std::string new_name = GetString(STR_PRESIDENT_NAME, c->index);
1270 AI::BroadcastNewEvent(new ScriptEventPresidentRenamed(c->index, new_name));
1271 Game::NewEvent(new ScriptEventPresidentRenamed(c->index, new_name));
1272 }
1273
1274 return CommandCost();
1275}
1276
1284{
1285 const VehicleDefaultSettings *vds = (c == nullptr) ? &_settings_client.company.vehicle : &c->settings.vehicle;
1286 switch (type) {
1287 default: NOT_REACHED();
1288 case VEH_TRAIN: return vds->servint_trains;
1289 case VEH_ROAD: return vds->servint_roadveh;
1290 case VEH_AIRCRAFT: return vds->servint_aircraft;
1291 case VEH_SHIP: return vds->servint_ships;
1292 }
1293}
1294
1301{
1302 uint32_t total = 0;
1303 for (RoadType rt : GetMaskForRoadTramType(rtt)) {
1304 total += this->road[rt];
1305 }
1306 return total;
1307}
1308
1320{
1322
1324 CommandCost amount(EXPENSES_OTHER, std::min<Money>(money, 20000000LL));
1325
1326 /* You can only transfer funds that is in excess of your loan */
1327 if (c->money - c->current_loan < amount.GetCost() || amount.GetCost() < 0) return CommandCost(STR_ERROR_INSUFFICIENT_FUNDS);
1328 if (!Company::IsValidID(dest_company)) return CMD_ERROR;
1329
1330 if (flags.Test(DoCommandFlag::Execute)) {
1331 /* Add money to company */
1333
1334 if (_networking) {
1335 std::string dest_company_name = GetString(STR_COMPANY_NAME, dest_company);
1336 std::string from_company_name = GetString(STR_COMPANY_NAME, _current_company);
1337
1338 NetworkTextMessage(NETWORK_ACTION_GIVE_MONEY, GetDrawStringCompanyColour(_current_company), false, from_company_name, dest_company_name, amount.GetCost());
1339 }
1340 }
1341
1342 /* Subtract money from local-company */
1343 return amount;
1344}
1345
1356{
1357 for (Company *c : Company::Iterate()) {
1358 if (Company::IsHumanID(c->index)) {
1359 return c->index;
1360 }
1361 }
1362
1364 for (CompanyID c = CompanyID::Begin(); c < MAX_COMPANIES; ++c) {
1365 if (!Company::IsValidID(c)) {
1366 return c;
1367 }
1368 }
1369 }
1370
1371 return CompanyID::Begin();
1372}
1373
1374static std::vector<FaceSpec> _faces;
1375
1380{
1381 _faces.clear();
1382 _faces.assign(std::begin(_original_faces), std::end(_original_faces));
1383}
1384
1390{
1391 return static_cast<uint>(std::size(_faces));
1392}
1393
1399const FaceSpec *GetCompanyManagerFaceSpec(uint style_index)
1400{
1401 if (style_index < GetNumCompanyManagerFaceStyles()) return &_faces[style_index];
1402 return nullptr;
1403}
1404
1410std::optional<uint> FindCompanyManagerFaceLabel(std::string_view label)
1411{
1412 auto it = std::ranges::find(_faces, label, &FaceSpec::label);
1413 if (it == std::end(_faces)) return std::nullopt;
1414
1415 return static_cast<uint>(std::distance(std::begin(_faces), it));
1416}
1417
1423FaceVars GetCompanyManagerFaceVars(uint style)
1424{
1425 const FaceSpec *spec = GetCompanyManagerFaceSpec(style);
1426 if (spec == nullptr) return {};
1427 return spec->GetFaceVars();
1428}
1429
1437{
1438 const FaceSpec *spec = GetCompanyManagerFaceSpec(style);
1439 assert(spec != nullptr);
1440
1441 cmf.style = style;
1442 cmf.style_label = spec->label;
1443}
1444
1456
1464uint32_t MaskCompanyManagerFaceBits(const CompanyManagerFace &cmf, FaceVars vars)
1465{
1466 CompanyManagerFace face{};
1467
1468 for (auto var : SetBitIterator(GetActiveFaceVars(cmf, vars))) {
1469 vars[var].SetBits(face, vars[var].GetBits(cmf));
1470 }
1471
1472 return face.bits;
1473}
1474
1481{
1482 uint32_t masked_face_bits = MaskCompanyManagerFaceBits(cmf, GetCompanyManagerFaceVars(cmf.style));
1483 return fmt::format("{}:{}", cmf.style_label, masked_face_bits);
1484}
1485
1491std::optional<CompanyManagerFace> ParseCompanyManagerFaceCode(std::string_view str)
1492{
1493 if (str.empty()) return std::nullopt;
1494
1496 StringConsumer consumer{str};
1497 if (consumer.FindChar(':') != StringConsumer::npos) {
1498 auto label = consumer.ReadUntilChar(':', StringConsumer::SKIP_ONE_SEPARATOR);
1499
1500 /* Read numeric part and ensure it's valid. */
1501 auto bits = consumer.TryReadIntegerBase<uint32_t>(10, true);
1502 if (!bits.has_value() || consumer.AnyBytesLeft()) return std::nullopt;
1503
1504 /* Ensure style label is valid. */
1505 auto style = FindCompanyManagerFaceLabel(label);
1506 if (!style.has_value()) return std::nullopt;
1507
1508 SetCompanyManagerFaceStyle(cmf, *style);
1509 cmf.bits = *bits;
1510 } else {
1511 /* No ':' included, treat as numeric-only. This allows old-style codes to be entered. */
1512 auto bits = ParseInteger(str, 10, true);
1513 if (!bits.has_value()) return std::nullopt;
1514
1515 /* Old codes use bits 0..1 to represent face style. These map directly to the default face styles. */
1516 SetCompanyManagerFaceStyle(cmf, GB(*bits, 0, 2));
1517 cmf.bits = *bits;
1518 }
1519
1520 /* Force the face bits to be valid. */
1521 FaceVars vars = GetCompanyManagerFaceVars(cmf.style);
1523 cmf.bits = MaskCompanyManagerFaceBits(cmf, vars);
1524
1525 return cmf;
1526}
Base functions for all AIs.
AIConfig stores the configuration settings of every AI.
The AIInstance tracks an AI.
Class for backupping variables and making sure they are restored later.
static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
static void BroadcastNewEvent(ScriptEvent *event, CompanyID skip_company=CompanyID::Invalid())
Broadcast a new event to all active AIs.
Definition ai_core.cpp:255
static bool CanStartNew()
Is it possible to start a new AI company?
Definition ai_core.cpp:30
static void StartNew(CompanyID company)
Start a new AI company.
Definition ai_core.cpp:36
static void Stop(CompanyID company)
Stop a company to be controlled by an AI.
Definition ai_core.cpp:107
static void NewEvent(CompanyID company, ScriptEvent *event)
Queue a new event for an AI.
Definition ai_core.cpp:235
constexpr bool All(const Timpl &other) const
Test if all of the values are set.
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr Timpl & Reset()
Reset all bits.
constexpr Timpl & Set()
Set all bits.
constexpr bool Any(const Timpl &other) const
Test if any of the given values are set.
Common return value for all commands.
ExpensesType GetExpensesType() const
The expense type of the cost.
void MakeError(StringID message)
Makes this CommandCost behave like an error command.
Money GetCost() const
The costs as made up to this moment.
void SetEncodedMessage(EncodedString &&message)
Set the encoded message string.
Container for an encoded string, created by GetEncodedString.
Enum-as-bit-set wrapper.
static void NewEvent(class ScriptEvent *event)
Queue a new event for a Game Script.
An interval timer will fire every interval, and will continue to fire until it is deleted.
Definition timer.h:76
bool Add(std::string_view key)
Add the given key to the authorized keys, when it is not already contained.
Definition network.cpp:189
bool Remove(std::string_view key)
Remove the given key from the authorized keys, when it is exists.
Definition network.cpp:205
Parse data from a string / buffer.
std::string_view ReadUntilChar(char c, SeparatorUsage sep)
Read data until the first occurrence of 8-bit char 'c', and advance reader.
@ SKIP_ONE_SEPARATOR
Read and discard one separator, do not include it in the result.
static constexpr size_type npos
Special value for "end of data".
static constexpr TimerGameTick::Ticks DAY_TICKS
1 day is 74 ticks; TimerGameCalendar::date_fract used to be uint16_t and incremented by 885.
static constexpr TimerGameTick::Ticks TICKS_PER_SECOND
Estimation of how many ticks fit in a single second.
A timeout timer will fire once after the interval.
Definition timer.h:116
void Abort()
Abort the timer so it doesn't fire if it hasn't yet.
Definition timer.h:161
static Year year
Current year, starting at 0.
static Year year
Current year, starting at 0.
A sort-of mixin that implements 'at(pos)' and 'operator[](pos)' only for a specific type.
Functions related to commands.
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
@ Execute
execute the given command
Definition of stuff that is very close to a company, like the company struct itself.
void ClearEnginesHiddenFlagOfCompany(CompanyID cid)
Clear the 'hidden' flag for all engines of a new company.
Definition engine.cpp:1008
void UpdateObjectColours(const Company *c)
Updates the colour of the object whenever a company changes.
TimeoutTimer< TimerGameTick > _new_competitor_timeout({ TimerGameTick::Priority::COMPETITOR_TIMEOUT, 0 }, []() { if(_game_mode==GM_MENU||!AI::CanStartNew()) return;if(_networking &&Company::GetNumItems() >=_settings_client.network.max_companies) return;if(_settings_game.difficulty.competitors_interval==0) return;uint8_t n=0;for(const Company *c :Company::Iterate()) { if(c->is_ai) n++;} if(n >=_settings_game.difficulty.max_no_competitors) return;Command< CMD_COMPANY_CTRL >::Post(CCA_NEW_AI, CompanyID::Invalid(), CRR_NONE, INVALID_CLIENT_ID);})
Start a new competitor company if possible.
std::optional< CompanyManagerFace > ParseCompanyManagerFaceCode(std::string_view str)
Parse a face code into a company manager face.
static void GenerateCompanyName(Company *c)
Generate the name of a company from the last build coordinate.
static bool IsValidCompanyManagerFace(CompanyManagerFace cmf)
Checks whether a company manager's face is a valid encoding.
const FaceSpec * GetCompanyManagerFaceSpec(uint style_index)
Get the definition of a company manager face style.
void OnTick_Companies()
Called every tick for updating some company info.
std::array< StringParameter, 2 > GetParamsForOwnedBy(Owner owner, TileIndex tile)
Set the right DParams for STR_ERROR_OWNED_BY.
FaceVars GetCompanyManagerFaceVars(uint style)
Get the face variables for a face style.
CommandCost CmdCompanyAllowListCtrl(DoCommandFlags flags, CompanyAllowListCtrlAction action, const std::string &public_key)
Add or remove the given public key to the allow list of this company.
void RandomiseCompanyManagerFace(CompanyManagerFace &cmf, Randomizer &randomizer)
Completely randomise a company manager face, including style.
void ResetFaces()
Reset company manager face styles to default.
Company * DoStartupNewCompany(bool is_ai, CompanyID company=CompanyID::Invalid())
Create a new company and sets all company variables default values.
void DrawCompanyIcon(CompanyID c, int x, int y)
Draw the icon of a company.
uint32_t MaskCompanyManagerFaceBits(const CompanyManagerFace &cmf, FaceVars vars)
Mask company manager face bits to ensure they are all within range.
std::string _company_manager_face
for company manager face storage in openttd.cfg
static Colours GenerateCompanyColour()
Generate a company colour.
static void GeneratePresidentName(Company *c)
Generate a random president name of a company.
static const Colours _similar_colour[COLOUR_END][2]
Similar colours, so we can try to prevent same coloured companies.
TypedIndexContainer< std::array< Colours, MAX_COMPANIES >, CompanyID > _company_colours
NOSAVE: can be determined from company structs.
void ResetCompanyLivery(Company *c)
Reset the livery schemes to the company's primary colour.
void UpdateCompanyLiveries(Company *c)
Update liveries for a company.
CommandCost CheckTileOwnership(TileIndex tile)
Check whether the current owner owns the stuff on the given tile.
CommandCost CmdSetCompanyColour(DoCommandFlags flags, LiveryScheme scheme, bool primary, Colours colour)
Change the company's company-colour.
CommandCost CmdCompanyCtrl(DoCommandFlags flags, CompanyCtrlAction cca, CompanyID company_id, CompanyRemoveReason reason, ClientID client_id)
Control the companies: add, delete, etc.
static std::vector< FaceSpec > _faces
All company manager face styles.
void InvalidateCompanyWindows(const Company *company)
Mark all finance windows owned by a company as needing a refresh.
int CompanyServiceInterval(const Company *c, VehicleType type)
Get the service interval for the given company and vehicle type.
PaletteID GetCompanyPalette(CompanyID company)
Get the palette for recolouring with a company colour.
void SetCompanyManagerFaceStyle(CompanyManagerFace &cmf, uint style)
Set a company face style.
bool CheckCompanyHasMoney(CommandCost &cost)
Verify whether the company can pay the bill.
static void SubtractMoneyFromCompany(Company *c, const CommandCost &cost)
Deduct costs of a command from the money of a company.
CompanyID GetFirstPlayableCompanyID()
Get the index of the first available company.
static CompanyMask _dirty_company_finances
Bitmask of company finances that should be marked dirty.
TextColour GetDrawStringCompanyColour(CompanyID company)
Get the colour for DrawString-subroutines which matches the colour of the company.
CommandCost CmdSetCompanyManagerFace(DoCommandFlags flags, uint style, uint32_t bits)
Change the company manager's face.
Money GetAvailableMoneyForCommand()
This functions returns the money which can be used to execute a command.
void CompanyAdminUpdate(const Company *company)
Called whenever company related information changes in order to notify admins.
std::optional< uint > FindCompanyManagerFaceLabel(std::string_view label)
Find a company manager face style by label.
CommandCost CheckOwnership(Owner owner, TileIndex tile)
Check whether the current owner owns something.
void CompanyAdminRemove(CompanyID company_id, CompanyRemoveReason reason)
Called whenever a company is removed in order to notify admins.
CommandCost CmdRenamePresident(DoCommandFlags flags, const std::string &text)
Change the name of the president.
CompanyPool _company_pool("Company")
Pool of companies.
static const IntervalTimer< TimerGameEconomy > _economy_companies_yearly({TimerGameEconomy::YEAR, TimerGameEconomy::Priority::COMPANY}, [](auto) { for(Company *c :Company::Iterate()) { std::rotate(std::rbegin(c->yearly_expenses), std::rbegin(c->yearly_expenses)+1, std::rend(c->yearly_expenses));c->yearly_expenses[0].fill(0);InvalidateWindowData(WC_FINANCES, c->index);} if(_settings_client.gui.show_finances &&_local_company !=COMPANY_SPECTATOR) { ShowCompanyFinances(_local_company);Company *c=Company::Get(_local_company);if(c->num_valid_stat_ent > 5 &&c->old_economy[0].performance_history< c->old_economy[4].performance_history) { if(_settings_client.sound.new_year) SndPlayFx(SND_01_BAD_YEAR);} else { if(_settings_client.sound.new_year) SndPlayFx(SND_00_GOOD_YEAR);} } })
A year has passed, update the economic data of all companies, and perhaps show the financial overview...
uint GetNumCompanyManagerFaceStyles()
Get the number of company manager face styles.
std::string FormatCompanyManagerFaceCode(const CompanyManagerFace &cmf)
Get a face code representation of a company manager face.
Money GetAvailableMoney(CompanyID company)
Get the amount of money that a company has available, or INT64_MAX if there is no such valid company.
void UpdateLandscapingLimits()
Update the landscaping limits per company.
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
void InitializeCompanies()
Initialize the pool of companies.
uint _cur_company_tick_index
used to generate a name for one company that doesn't have a name yet per tick
void StartupCompanies()
Start of a new game.
bool CheckTakeoverVehicleLimit(CompanyID cbig, CompanyID csmall)
Can company cbig buy company csmall without exceeding vehicle limits?
static bool IsUniqueCompanyName(const std::string &name)
Is the given name in use as name of a company?
void SetLocalCompany(CompanyID new_company)
Sets the local company and updates the settings that are set on a per-company basis to reflect the co...
static bool IsUniquePresidentName(const std::string &name)
Is the given name in use as president name of a company?
CompanyID _current_company
Company currently doing an action.
CommandCost CmdGiveMoney(DoCommandFlags flags, Money money, CompanyID dest_company)
Transfer funds (money) from one company to another.
static void HandleBankruptcyTakeover(Company *c)
Handle the bankruptcy take over of a company.
CommandCost CmdRenameCompany(DoCommandFlags flags, const std::string &text)
Change the name of the company.
void SubtractMoneyFromCompanyFract(CompanyID company, const CommandCost &cst)
Subtract money from a company, including the money fraction.
static const IntervalTimer< TimerWindow > invalidate_company_windows_interval(std::chrono::milliseconds(1), [](auto) { for(CompanyID cid :_dirty_company_finances) { if(cid==_local_company) SetWindowWidgetDirty(WC_STATUS_BAR, 0, WID_S_RIGHT);Window *w=FindWindowById(WC_FINANCES, cid);if(w !=nullptr) { w->SetWidgetDirty(WID_CF_EXPS_PRICE3);w->SetWidgetDirty(WID_CF_OWN_VALUE);w->SetWidgetDirty(WID_CF_LOAN_VALUE);w->SetWidgetDirty(WID_CF_BALANCE_VALUE);w->SetWidgetDirty(WID_CF_MAXLOAN_VALUE);} SetWindowWidgetDirty(WC_COMPANY, cid, WID_C_DESC_COMPANY_VALUE);} _dirty_company_finances.Reset();})
Refresh all company finance windows previously marked dirty.
static const uint8_t _colour_sort[COLOUR_END]
Sorting weights for the company colours.
Command definitions related to companies.
This file contains all definitions for default company faces.
static FaceSpec _original_faces[]
Original face styles.
Functions related to companies.
bool IsInteractiveCompany(CompanyID company)
Is the user representing company?
void ChangeOwnershipOfCompanyItems(Owner old_owner, Owner new_owner)
Change the ownership of all the items of a company.
Definition economy.cpp:322
void ShowBuyCompanyDialog(CompanyID company, bool hostile_takeover)
Show the query to buy another company.
bool IsLocalCompany()
Is the current company the local company?
void ShowCompanyFinances(CompanyID company)
Open the finances window of a company.
GUI Functions related to companies.
void CloseCompanyWindows(CompanyID company)
Close all windows of a company.
Definition window.cpp:1223
Functionality related to the company manager's face.
void RandomiseCompanyManagerFaceBits(CompanyManagerFace &cmf, FaceVars vars, Randomizer &randomizer)
Make a random new face without changing the face style.
uint64_t GetActiveFaceVars(const CompanyManagerFace &cmf, FaceVars vars)
Get a bitmask of currently active face variables.
void ScaleAllCompanyManagerFaceBits(CompanyManagerFace &cmf, FaceVars vars)
Scales all company manager's face bits to the correct scope.
static const uint MAX_LENGTH_PRESIDENT_NAME_CHARS
The maximum length of a president name in characters including '\0'.
static const uint MAX_LENGTH_COMPANY_NAME_CHARS
The maximum length of a company name in characters including '\0'.
CompanyCtrlAction
The action to do with CMD_COMPANY_CTRL.
@ CCA_NEW_AI
Create a new AI company.
@ CCA_DELETE
Delete a company.
@ CCA_NEW
Create a new company.
static constexpr CompanyID COMPANY_SPECTATOR
The client is spectating.
static constexpr Owner OWNER_END
Last + 1 owner.
CompanyAllowListCtrlAction
The action to do with CMD_COMPANY_ALLOW_LIST_CTRL.
@ CALCA_REMOVE
Remove a public key.
@ CALCA_ADD
Create a public key.
static constexpr Owner OWNER_TOWN
A town owns the tile, or a town is expanding.
static constexpr Owner OWNER_NONE
The tile has no ownership.
static constexpr Owner INVALID_OWNER
An invalid owner.
CompanyRemoveReason
The reason why the company was removed.
@ CRR_END
Sentinel for end.
@ CRR_NONE
Dummy reason for actions that don't need one.
@ WID_CF_OWN_VALUE
Own funds, not including loan.
@ WID_CF_LOAN_VALUE
Loan.
@ WID_CF_BALANCE_VALUE
Bank balance value.
@ WID_CF_EXPS_PRICE3
Column for year Y expenses.
@ WID_CF_MAXLOAN_VALUE
Max loan widget.
@ WID_C_DESC_COMPANY_VALUE
Company value.
@ WID_C_PRESIDENT_NAME
Button to change president name.
@ WID_C_COMPANY_NAME
Button to change company name.
static const uint NETWORK_PUBLIC_KEY_LENGTH
The maximum length of the hexadecimal encoded public keys, in bytes including '\0'.
Definition config.h:99
@ EXPENSES_ROADVEH_RUN
Running costs road vehicles.
@ EXPENSES_TRAIN_RUN
Running costs trains.
@ EXPENSES_AIRCRAFT_REVENUE
Revenue from aircraft.
@ EXPENSES_AIRCRAFT_RUN
Running costs aircraft.
@ EXPENSES_ROADVEH_REVENUE
Revenue from road vehicles.
@ EXPENSES_PROPERTY
Property costs.
@ EXPENSES_OTHER
Other expenses.
@ EXPENSES_SHIP_REVENUE
Revenue from ships.
@ EXPENSES_LOAN_INTEREST
Interest payments over the loan.
@ EXPENSES_TRAIN_REVENUE
Revenue from trains.
@ EXPENSES_SHIP_RUN
Running costs ships.
@ INVALID_EXPENSES
Invalid expense type.
static const int LOAN_INTERVAL
The "steps" in loan size, in British Pounds!
static const int64_t INITIAL_LOAN
The size of loan for a new company, in British Pounds!
Base functions for all Games.
void DrawSprite(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub, ZoomLevel zoom)
Draw a sprite, not in a viewport.
Definition gfx.cpp:1034
uint32_t PaletteID
The number of the palette.
Definition gfx_type.h:18
TextColour
Colour of the strings, see _string_colourmap in table/string_colours.h or docs/ottd-colourtext-palett...
Definition gfx_type.h:307
Goal base class.
void UpdateCompanyGroupLiveries(const Company *c)
Update group liveries for a company.
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition gfx.cpp:1549
@ Random
Randomise borders.
LiveryScheme
List of different livery schemes.
Definition livery.h:22
constexpr bool IsInsideMM(const size_t x, const size_t min, const size_t max) noexcept
Checks if a value is in an interval.
bool _networking
are we in networking mode?
Definition network.cpp:66
bool _network_server
network-server is active
Definition network.cpp:67
ClientID _network_own_client_id
Our client identifier.
Definition network.cpp:71
Basic functions/variables used all over the place.
void NetworkAdminCompanyUpdate(const Company *company)
Notify the admin network of company updates.
void NetworkAdminCompanyNew(const Company *company)
Notify the admin network of a new company.
void NetworkAdminCompanyRemove(CompanyID company_id, AdminCompanyRemoveReason bcrr)
Notify the admin network of a company to be removed (including the reason why).
Server part of the admin network protocol.
Base core network types and some helper functions to access them.
Network functions used by other parts of OpenTTD.
void NetworkServerNewCompany(const Company *company, NetworkClientInfo *ci)
Perform all the server specific administration of a new company.
void NetworkUpdateClientInfo(ClientID client_id)
Send updated client info of a particular client.
@ DESTTYPE_TEAM
Send message/notice to everyone playing the same company (Team)
ClientID
'Unique' identifier to be given to clients
@ INVALID_CLIENT_ID
Client is not part of anything.
Functions related to news.
void AddNewsItem(EncodedString &&headline, NewsType type, NewsStyle style, NewsFlags flags, NewsReference ref1={}, NewsReference ref2={}, std::unique_ptr< NewsAllocatedData > &&data=nullptr, AdviceType advice_type=AdviceType::Invalid)
Add a new newsitem to be shown.
Definition news_gui.cpp:900
@ CompanyInfo
Company info (new companies, bankruptcy messages)
@ Company
Company news item. (Newspaper with face)
PixelColour GetColourGradient(Colours colour, ColourShade shade)
Get colour gradient palette index.
Definition palette.cpp:388
Some methods of Pool are placed here in order to reduce compilation time and binary size.
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don't get linker errors.
RailTypes GetCompanyRailTypes(CompanyID company, bool introduces)
Get the rail types the given company can build.
Definition rail.cpp:135
Rail specific functions.
Randomizer _random
Random used in the game state calculations.
RoadTypes GetCompanyRoadTypes(CompanyID company, bool introduces)
Get the road types the given company can build.
Definition road.cpp:210
RoadTypes GetMaskForRoadTramType(RoadTramType rtt)
Get the mask for road types of the given RoadTramType.
Definition road.h:183
RoadTramType
The different types of road type.
Definition road_type.h:37
RoadType
The different roadtypes we support.
Definition road_type.h:23
A number of safeguards to prevent using unsafe methods.
void SyncCompanySettings()
Sync all company settings in a multiplayer game.
void SetDefaultCompanySettings(CompanyID cid)
Set the company settings for a new company to their default values.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:61
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:60
Functions related to setting/changing the settings.
void BuildOwnerLegend()
Completes the array for the owned property legend.
Smallmap GUI functions.
Functions related to sound.
@ SND_01_BAD_YEAR
40 == 0x28 New year: performance declined
Definition sound_type.h:87
@ SND_00_GOOD_YEAR
39 == 0x27 New year: performance improved
Definition sound_type.h:86
static PaletteID GetColourPalette(Colours colour)
Get recolour palette for a colour.
Definition sprite.h:188
Types related to the statusbar widgets.
@ WID_S_RIGHT
Right part; bank balance.
Definition of base types and functions in a cross-platform compatible way.
StoryPage base class.
size_t Utf8StringLength(std::string_view str)
Get the length of an UTF-8 encoded string in number of characters and thus not the number of bytes th...
Definition string.cpp:349
Parse strings.
static std::optional< T > ParseInteger(std::string_view arg, int base=10, bool clamp=false)
Change a string into its number representation.
EncodedString GetEncodedStringWithArgs(StringID str, std::span< const StringParameter > params)
Encode a string with its parameters into an encoded string.
Definition strings.cpp:102
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:90
std::string GetString(StringID string)
Resolve the given StringID into a std::string with formatting but no parameters.
Definition strings.cpp:424
Functions related to OTTD's strings.
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
static constexpr StringID SPECSTR_COMPANY_NAME_START
Special strings for company names on the form "TownName transport".
static constexpr StringID SPECSTR_ANDCO_NAME
Special string for Surname & Co company names.
static constexpr StringID SPECSTR_PRESIDENT_NAME
Special string for the president's name.
static constexpr StringID SPECSTR_TOWNNAME_START
Special strings for town names.
CompanySettings company
default values for per-company settings
NetworkSettings network
settings related to the network
SoundSettings sound
sound effect settings
GUISettings gui
settings related to the GUI
Money income
The amount of income.
Money expenses
The amount of expenses.
uint32_t GetRoadTramTotal(RoadTramType rtt) const
Get total sum of all owned road bits.
std::array< uint32_t, ROADTYPE_END > road
Count of company owned track bits for each road type.
uint32_t bits
Company manager face bits, meaning is dependent on style.
uint style
Company manager face style.
std::string style_label
Face style label.
CompanyManagerFace face
The face of the president.
Definition news_type.h:168
Colours colour
The colour related to the company.
Definition news_type.h:169
CompanyNewsInformation(StringID title, const struct Company *c, const struct Company *other=nullptr)
Fill the CompanyNewsInformation struct with the required data.
std::string president_name
The name of the president.
Definition news_type.h:164
std::string company_name
The name of the company.
Definition news_type.h:163
std::string other_company_name
The name of the company taking over this one.
Definition news_type.h:165
CompanyMask bankrupt_asked
which companies were asked about buying it?
std::string president_name
Name of the president if the user changed it.
int16_t bankrupt_timeout
If bigger than 0, amount of time to wait for an answer on an offer to buy this company.
CompanySettings settings
settings specific for each company
NetworkAuthorizedKeys allow_list
Public keys of clients that are allowed to join this company.
uint32_t name_2
Parameter of name_1.
uint8_t money_fraction
Fraction of money of the company, too small to represent in money.
bool is_ai
If true, the company is (also) controlled by the computer (a NoAI program).
uint32_t president_name_2
Parameter of president_name_1.
StringID name_1
Name of the company if the user did not change it.
Money current_loan
Amount of money borrowed from the bank.
TimerGameCalendar::Year inaugurated_year_calendar
Calendar year of starting the company. Used to display proper Inauguration year while in wallclock mo...
TimerGameEconomy::Year inaugurated_year
Economy year of starting the company.
CompanyEconomyEntry cur_economy
Economic data of the company of this quarter.
Colours colour
Company colour.
std::array< CompanyEconomyEntry, MAX_HISTORY_QUARTERS > old_economy
Economic data of the company of the last MAX_HISTORY_QUARTERS quarters.
CompanyManagerFace face
Face description of the president.
Money max_loan
Max allowed amount of the loan or COMPANY_MAX_LOAN_DEFAULT.
std::array< Expenses, 3 > yearly_expenses
Expenses of the company for the last three years.
TileIndex last_build_coordinate
Coordinate of the last build thing by this company.
StringID president_name_1
Name of the president if the user did not change it.
std::string name
Name of the company if the user changed it.
Money money
Money owned by the company.
uint8_t num_valid_stat_ent
Number of valid statistical entries in old_economy.
VehicleDefaultSettings vehicle
default settings for vehicles
Money GetMaxLoan() const
Calculate the max allowed loan for this company.
static bool IsHumanID(auto index)
Is this company a company not controlled by a NoAI program?
std::array< GroupStatistics, VEH_COMPANY_END > group_all
NOSAVE: Statistics for the ALL_GROUP group.
RoadTypes avail_roadtypes
Road types available to this company.
~Company()
Destructor.
RailTypes avail_railtypes
Rail types available to this company.
static void PostDestructor(size_t index)
Invalidating some stuff after removing item from the pool.
uint32_t clear_per_64k_frames
how many tiles may, over a long period, be cleared per 65536 frames?
uint32_t tree_per_64k_frames
how many trees may, over a long period, be planted per 65536 frames?
uint16_t terraform_frame_burst
how many tile heights may, over a short period, be terraformed?
uint16_t tree_frame_burst
how many trees may, over a short period, be planted?
uint16_t build_object_frame_burst
how many tiles may, over a short period, be purchased or have objects built on them?
uint32_t build_object_per_64k_frames
how many tiles may, over a long period, be purchased or have objects built on them per 65536 frames?
uint32_t terraform_per_64k_frames
how many tile heights may, over a long period, be terraformed per 65536 frames?
uint16_t clear_frame_burst
how many tiles may, over a short period, be cleared?
uint8_t max_no_competitors
the number of competitors (AIs)
bool infinite_money
whether spending money despite negative balance is allowed
uint16_t competitors_interval
the interval (in minutes) between adding competitors
bool give_money
allow giving other companies money
uint64_t inflation_prices
Cumulated inflation of prices since game start; 16 bit fractional part.
Money max_loan
NOSAVE: Maximum possible loan.
bool show_finances
show finances at end of year
EconomySettings economy
settings to change the economy
ConstructionSettings construction
construction of things in-game
DifficultySettings difficulty
settings related to the difficulty
VehicleSettings vehicle
options for vehicles
Group data.
Definition group.h:73
@ Primary
Primary colour is set.
@ Secondary
Secondary colour is set.
Container for all information known about a client.
static NetworkClientInfo * GetByClientID(ClientID client_id)
Return the CI given it's client-identifier.
Definition network.cpp:117
CompanyID client_playas
As which company is this client playing (CompanyID)
ClientID client_id
Client identifier (same as ClientState->client_id)
uint8_t max_companies
maximum amount of companies
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
static T * Create(Targs &&... args)
Creates a new T-object in the associated pool.
static T * CreateAtIndex(Tindex index, Targs &&... args)
Creates a new T-object in the associated pool.
static Titem * Get(auto index)
Returns Titem with given index.
static size_t GetNumItems()
Returns number of valid items in the pool.
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function()
static bool IsValidID(auto index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
const Tindex index
Index of this pool item.
static bool CleaningPool()
Returns current state of pool cleaning - yes or no.
static Titem * GetIfValid(auto index)
Returns Titem with given index.
Base class for all pools.
Structure to encapsulate the pseudo random number generators.
uint32_t Next()
Generate the next pseudo random number.
Iterable ensemble of each set bit in a value.
bool new_year
Play sound on new year, summarising the performance during the last year.
Town data structure.
Definition town.h:63
std::string name
Custom town name. If empty, the town was not renamed and uses the generated name.
Definition town.h:72
Default settings for vehicles.
uint16_t servint_aircraft
service interval for aircraft
uint16_t servint_roadveh
service interval for road vehicles
uint16_t servint_ships
service interval for ships
uint16_t servint_trains
service interval for trains
UnitID max_ships
max ships in game per company
UnitID max_trains
max trains in game per company
UnitID max_aircraft
max planes in game per company
UnitID max_roadveh
max trucks in game per company
Vehicle data structure.
Data structure for an opened window.
Definition window_gui.h:274
void SetWidgetDirty(WidgetID widget_index) const
Invalidate a widget, i.e.
Definition window.cpp:558
AdminCompanyRemoveReason
Reasons for removing a company - communicated to admins.
Definition tcp_admin.h:105
Owner GetTileOwner(Tile tile)
Returns the owner of a tile.
Definition tile_map.h:178
Definition of Interval and OneShot timers.
Definition of the game-economy-timer.
Definition of the tick-based game-timer.
Definition of the Window system.
Base of the town class.
Town * ClosestTownFromTile(TileIndex tile, uint threshold)
Return the town closest (in distance or ownership) to a given tile, within a given threshold.
Base class for all vehicles.
Functions related to vehicles.
VehicleType
Available vehicle types.
@ VEH_ROAD
Road vehicle type.
@ VEH_AIRCRAFT
Aircraft vehicle type.
@ VEH_SHIP
Ship vehicle type.
@ VEH_TRAIN
Train vehicle type.
void CloseConstructionWindows()
Close all windows that are used for construction of vehicle etc.
Definition window.cpp:3387
void CloseWindowById(WindowClass cls, WindowNumber number, bool force, int data)
Close a window by its class and window number (if it is open).
Definition window.cpp:1195
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
Definition window.cpp:3300
Window * FindWindowById(WindowClass cls, WindowNumber number)
Find a window by its class and window number.
Definition window.cpp:1153
void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, WidgetID widget_index)
Mark a particular widget in a particular window as dirty (in need of repainting)
Definition window.cpp:3194
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition window.cpp:3178
void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
Mark window data of all windows of a given class as invalid (in need of re-computing) Note that by de...
Definition window.cpp:3318
Window functions not directly related to making/drawing windows.
@ WN_NETWORK_STATUS_WINDOW_JOIN
Network join status.
Definition window_type.h:44
@ WC_PERFORMANCE_HISTORY
Performance history graph; Window numbers:
@ WC_COMPANY_LEAGUE
Company league window; Window numbers:
@ WC_SIGN_LIST
Sign list; Window numbers:
@ WC_PERFORMANCE_DETAIL
Performance detail window; Window numbers:
@ WC_COMPANY_COLOUR
Company colour selection; Window numbers:
@ WC_GRAPH_LEGEND
Legend for graphs; Window numbers:
@ WC_LINKGRAPH_LEGEND
Linkgraph legend; Window numbers:
@ WC_STATUS_BAR
Statusbar (at the bottom of your screen); Window numbers:
Definition window_type.h:69
@ WC_SEND_NETWORK_MSG
Chatbox; Window numbers:
@ WC_ERRMSG
Error message; Window numbers:
@ WC_SCRIPT_SETTINGS
Script settings; Window numbers:
@ WC_SCRIPT_LIST
Scripts list; Window numbers:
@ WC_GOALS_LIST
Goals list; Window numbers:
@ WC_OPERATING_PROFIT
Operating profit graph; Window numbers:
@ WC_CLIENT_LIST
Client list; Window numbers:
@ WC_GAME_OPTIONS
Game options window; Window numbers:
@ WC_FINANCES
Finances of a company; Window numbers:
@ WC_INCOME_GRAPH
Income graph; Window numbers:
@ WC_SMALLMAP
Small map; Window numbers:
@ WC_DELIVERED_CARGO
Delivered cargo graph; Window numbers:
@ WC_COMPANY_VALUE
Company value graph; Window numbers:
@ WC_MAIN_TOOLBAR
Main toolbar (the long bar at the top); Window numbers:
Definition window_type.h:63
@ WC_COMPANY
Company view; Window numbers:
@ WC_NETWORK_STATUS_WINDOW
Network status window; Window numbers: