4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
10 /** @file company_cmd.cpp Handling of companies. */
14 #include "company_base.h"
15 #include "company_func.h"
16 #include "company_gui.h"
18 #include "news_func.h"
19 #include "cmd_helper.h"
20 #include "command_func.h"
21 #include "network/network.h"
22 #include "network/network_func.h"
23 #include "network/network_base.h"
24 #include "network/network_admin.h"
26 #include "company_manager_face.h"
27 #include "window_func.h"
28 #include "strings_func.h"
29 #include "date_func.h"
30 #include "sound_func.h"
32 #include "core/pool_func.hpp"
33 #include "settings_func.h"
34 #include "vehicle_base.h"
35 #include "vehicle_func.h"
36 #include "smallmap_gui.h"
37 #include "game/game.hpp"
38 #include "goal_base.h"
39 #include "story_base.h"
40 #include "map/common.h"
42 #include "table/strings.h"
44 void ClearEnginesHiddenFlagOfCompany(CompanyID cid
);
46 CompanyByte _local_company
; ///< Company controlled by the human player at this client. Can also be #COMPANY_SPECTATOR.
47 CompanyByte _current_company
; ///< Company currently doing an action.
48 Colours _company_colours
[MAX_COMPANIES
]; ///< NOSAVE: can be determined from company structs.
49 CompanyManagerFace _company_manager_face
; ///< for company manager face storage in openttd.cfg
50 uint _next_competitor_start
; ///< the number of ticks before the next AI is started
51 uint _cur_company_tick_index
; ///< used to generate a name for one company that doesn't have a name yet per tick
53 template<> Company::Pool
Company::PoolItem::pool ("Company");
54 INSTANTIATE_POOL_METHODS(Company
)
58 * @param name_1 Name of the company.
59 * @param is_ai A computer program is running for this company.
61 Company::Company(uint16 name_1
, bool is_ai
)
63 this->name_1
= name_1
;
64 this->location_of_HQ
= INVALID_TILE
;
66 this->terraform_limit
= _settings_game
.construction
.terraform_frame_burst
<< 16;
67 this->clear_limit
= _settings_game
.construction
.clear_frame_burst
<< 16;
68 this->tree_limit
= _settings_game
.construction
.tree_frame_burst
<< 16;
70 for (uint j
= 0; j
< 4; j
++) this->share_owners
[j
] = COMPANY_SPECTATOR
;
71 InvalidateWindowData(WC_PERFORMANCE_DETAIL
, 0, INVALID_COMPANY
);
77 if (CleaningPool()) return;
79 DeleteCompanyWindows(this->index
);
83 * Invalidating some stuff after removing item from the pool.
84 * @param index index of deleted item
86 void Company::PostDestructor(size_t index
)
88 InvalidateWindowData(WC_GRAPH_LEGEND
, 0, (int)index
);
89 InvalidateWindowData(WC_PERFORMANCE_DETAIL
, 0, (int)index
);
90 InvalidateWindowData(WC_COMPANY_LEAGUE
, 0, 0);
91 InvalidateWindowData(WC_LINKGRAPH_LEGEND
, 0);
92 /* If the currently shown error message has this company in it, then close it. */
93 InvalidateWindowData(WC_ERRMSG
, 0);
97 * Sets the local company and updates the settings that are set on a
98 * per-company basis to reflect the core's state in the GUI.
99 * @param new_company the new company
100 * @pre Company::IsValidID(new_company) || new_company == COMPANY_SPECTATOR || new_company == OWNER_NONE
102 void SetLocalCompany(CompanyID new_company
)
104 /* company could also be COMPANY_SPECTATOR or OWNER_NONE */
105 assert(Company::IsValidID(new_company
) || new_company
== COMPANY_SPECTATOR
|| new_company
== OWNER_NONE
);
107 #ifdef ENABLE_NETWORK
108 /* Delete the chat window, if you were team chatting. */
109 InvalidateWindowData(WC_SEND_NETWORK_MSG
, DESTTYPE_TEAM
, _local_company
);
112 assert(IsLocalCompany());
114 _current_company
= _local_company
= new_company
;
116 /* Delete any construction windows... */
117 DeleteConstructionWindows();
119 /* ... and redraw the whole screen. */
120 MarkWholeScreenDirty();
121 InvalidateWindowClassesData(WC_SIGN_LIST
, -1);
125 * Get the colour for DrawString-subroutines which matches the colour of the company.
126 * @param company Company to get the colour of.
127 * @return Colour of \a company.
129 TextColour
GetDrawStringCompanyColour(CompanyID company
)
131 if (!Company::IsValidID(company
)) return (TextColour
)_colour_gradient
[COLOUR_WHITE
][4] | TC_IS_PALETTE_COLOUR
;
132 return (TextColour
)_colour_gradient
[_company_colours
[company
]][4] | TC_IS_PALETTE_COLOUR
;
136 * Draw the icon of a company.
137 * @param dpi Area to draw on.
138 * @param c Company that needs its icon drawn.
139 * @param x Horizontal coordinate of the icon.
140 * @param y Vertical coordinate of the icon.
142 void DrawCompanyIcon (BlitArea
*dpi
, CompanyID c
, int x
, int y
)
144 DrawSprite (dpi
, SPR_COMPANY_ICON
, COMPANY_SPRITE_COLOUR(c
), x
, y
);
148 * Checks whether a company manager's face is a valid encoding.
149 * Unused bits are not enforced to be 0.
150 * @param cmf the fact to check
151 * @return true if and only if the face is valid
153 static bool IsValidCompanyManagerFace(CompanyManagerFace cmf
)
155 if (!AreCompanyManagerFaceBitsValid(cmf
, CMFV_GEN_ETHN
, GE_WM
)) return false;
157 GenderEthnicity ge
= (GenderEthnicity
)GetCompanyManagerFaceBits(cmf
, CMFV_GEN_ETHN
, GE_WM
);
158 bool has_moustache
= !HasBit(ge
, GENDER_FEMALE
) && GetCompanyManagerFaceBits(cmf
, CMFV_HAS_MOUSTACHE
, ge
) != 0;
159 bool has_tie_earring
= !HasBit(ge
, GENDER_FEMALE
) || GetCompanyManagerFaceBits(cmf
, CMFV_HAS_TIE_EARRING
, ge
) != 0;
160 bool has_glasses
= GetCompanyManagerFaceBits(cmf
, CMFV_HAS_GLASSES
, ge
) != 0;
162 if (!AreCompanyManagerFaceBitsValid(cmf
, CMFV_EYE_COLOUR
, ge
)) return false;
163 for (CompanyManagerFaceVariable cmfv
= CMFV_CHEEKS
; cmfv
< CMFV_END
; cmfv
++) {
165 case CMFV_MOUSTACHE
: if (!has_moustache
) continue; break;
167 case CMFV_NOSE
: if (has_moustache
) continue; break;
168 case CMFV_TIE_EARRING
: if (!has_tie_earring
) continue; break;
169 case CMFV_GLASSES
: if (!has_glasses
) continue; break;
172 if (!AreCompanyManagerFaceBitsValid(cmf
, cmfv
, ge
)) return false;
179 * Refresh all windows owned by a company.
180 * @param company Company that changed, and needs its windows refreshed.
182 void InvalidateCompanyWindows(const Company
*company
)
184 CompanyID cid
= company
->index
;
186 if (cid
== _local_company
) SetWindowDirty(WC_STATUS_BAR
, 0);
187 SetWindowDirty(WC_FINANCES
, cid
);
191 * Verify whether the company can pay the bill.
192 * @param cost [inout] Money to pay, is changed to an error if the company does not have enough money.
193 * @return Function returns \c true if the company has enough money, else it returns \c false.
195 bool CheckCompanyHasMoney(CommandCost
&cost
)
197 if (cost
.GetCost() > 0) {
198 const Company
*c
= Company::GetIfValid(_current_company
);
199 if (c
!= NULL
&& cost
.GetCost() > c
->money
) {
200 SetDParam(0, cost
.GetCost());
201 cost
.MakeError(STR_ERROR_NOT_ENOUGH_CASH_REQUIRES_CURRENCY
);
209 * Deduct costs of a command from the money of a company.
210 * @param c Company to pay the bill.
211 * @param cost Money to pay.
213 static void SubtractMoneyFromAnyCompany(Company
*c
, CommandCost cost
)
215 if (cost
.GetCost() == 0) return;
216 assert(cost
.GetExpensesType() != INVALID_EXPENSES
);
218 c
->money
-= cost
.GetCost();
219 c
->yearly_expenses
[0][cost
.GetExpensesType()] += cost
.GetCost();
221 if (HasBit(1 << EXPENSES_TRAIN_INC
|
222 1 << EXPENSES_ROADVEH_INC
|
223 1 << EXPENSES_AIRCRAFT_INC
|
224 1 << EXPENSES_SHIP_INC
, cost
.GetExpensesType())) {
225 c
->cur_economy
.income
-= cost
.GetCost();
226 } else if (HasBit(1 << EXPENSES_TRAIN_RUN
|
227 1 << EXPENSES_ROADVEH_RUN
|
228 1 << EXPENSES_AIRCRAFT_RUN
|
229 1 << EXPENSES_SHIP_RUN
|
230 1 << EXPENSES_PROPERTY
|
231 1 << EXPENSES_LOAN_INT
, cost
.GetExpensesType())) {
232 c
->cur_economy
.expenses
-= cost
.GetCost();
235 InvalidateCompanyWindows(c
);
239 * Subtract money from the #_current_company, if the company is valid.
240 * @param cost Money to pay.
242 void SubtractMoneyFromCompany(CommandCost cost
)
244 Company
*c
= Company::GetIfValid(_current_company
);
245 if (c
!= NULL
) SubtractMoneyFromAnyCompany(c
, cost
);
249 * Subtract money from a company, including the money fraction.
250 * @param company Company paying the bill.
251 * @param cst Cost of a command.
253 void SubtractMoneyFromCompanyFract(CompanyID company
, CommandCost cst
)
255 Company
*c
= Company::Get(company
);
256 byte m
= c
->money_fraction
;
257 Money cost
= cst
.GetCost();
259 c
->money_fraction
= m
- (byte
)cost
;
261 if (c
->money_fraction
> m
) cost
++;
262 if (cost
!= 0) SubtractMoneyFromAnyCompany(c
, CommandCost(cst
.GetExpensesType(), cost
));
265 /** Update the landscaping limits per company. */
266 void UpdateLandscapingLimits()
269 FOR_ALL_COMPANIES(c
) {
270 c
->terraform_limit
= min(c
->terraform_limit
+ _settings_game
.construction
.terraform_per_64k_frames
, (uint32
)_settings_game
.construction
.terraform_frame_burst
<< 16);
271 c
->clear_limit
= min(c
->clear_limit
+ _settings_game
.construction
.clear_per_64k_frames
, (uint32
)_settings_game
.construction
.clear_frame_burst
<< 16);
272 c
->tree_limit
= min(c
->tree_limit
+ _settings_game
.construction
.tree_per_64k_frames
, (uint32
)_settings_game
.construction
.tree_frame_burst
<< 16);
277 * Set the right DParams to get the name of an owner.
278 * @param owner the owner to get the name of.
279 * @param tile optional tile to get the right town.
280 * @pre if tile == 0, then owner can't be OWNER_TOWN.
282 void GetNameOfOwner(Owner owner
, TileIndex tile
)
286 if (owner
!= OWNER_TOWN
) {
287 if (!Company::IsValidID(owner
)) {
288 SetDParam(0, STR_COMPANY_SOMEONE
);
290 SetDParam(0, STR_COMPANY_NAME
);
295 const Town
*t
= ClosestTownFromTile(tile
);
297 SetDParam(0, STR_TOWN_NAME
);
298 SetDParam(1, t
->index
);
304 * Check whether the current owner owns something.
305 * If that isn't the case an appropriate error will be given.
306 * @param owner the owner of the thing to check.
307 * @param tile optional tile to get the right town.
308 * @pre if tile == 0 then the owner can't be OWNER_TOWN.
309 * @return A succeeded command iff it's owned by the current company, else a failed command.
311 CommandCost
CheckOwnership(Owner owner
, TileIndex tile
)
313 assert(owner
< OWNER_END
);
314 assert(owner
!= OWNER_TOWN
|| tile
!= 0);
316 if (owner
== _current_company
) return CommandCost();
318 GetNameOfOwner(owner
, tile
);
319 return_cmd_error(STR_ERROR_OWNED_BY
);
323 * Check whether the current owner owns the stuff on
324 * the given tile. If that isn't the case an
325 * appropriate error will be given.
326 * @param tile the tile to check.
327 * @return A succeeded command iff it's owned by the current company, else a failed command.
329 CommandCost
CheckTileOwnership(TileIndex tile
)
331 Owner owner
= GetTileOwner(tile
);
333 assert(owner
< OWNER_END
);
335 if (owner
== _current_company
) return CommandCost();
337 /* no need to get the name of the owner unless we're the local company (saves some time) */
338 if (IsLocalCompany()) GetNameOfOwner(owner
, tile
);
339 return_cmd_error(STR_ERROR_OWNED_BY
);
342 /** Check if the given components are unique for a company name. */
343 static bool CheckUniqueCompanyNameParts (StringID str
, uint32 strp
)
345 /* Reserve space for extra unicode character. We need to do this
346 * to be able to detect too long company name. */
347 char buffer
[(MAX_LENGTH_COMPANY_NAME_CHARS
+ 1) * MAX_CHAR_LENGTH
];
350 FOR_ALL_COMPANIES(c
) {
351 if (c
->name_1
== str
&& c
->name_2
== strp
) return false;
354 GetString (buffer
, str
);
355 return Utf8StringLength(buffer
) < MAX_LENGTH_COMPANY_NAME_CHARS
;
359 * Generate the name of a company from the last build coordinate.
360 * @param c Company to give a name.
362 static void GenerateCompanyName(Company
*c
)
364 if (c
->name_1
!= STR_SV_UNNAMED
) return;
365 if (c
->last_build_coordinate
== 0) return;
367 Town
*t
= ClosestTownFromTile(c
->last_build_coordinate
);
371 if (t
->name
== NULL
&& IsInsideMM (t
->townnameparams
.type
, SPECSTR_TOWNNAME_START
, SPECSTR_TOWNNAME_LAST
+ 1)) {
372 str
= t
->townnameparams
.type
- SPECSTR_TOWNNAME_START
+ SPECSTR_COMPANY_NAME_START
;
373 strp
= t
->townnameparts
;
375 /* No companies must have this name already */
376 if (CheckUniqueCompanyNameParts (str
, strp
)) goto set_name
;
379 str
= SPECSTR_ANDCO_NAME
;
380 if (c
->president_name_1
== SPECSTR_PRESIDENT_NAME
) {
381 strp
= c
->president_name_2
;
387 } while (!CheckUniqueCompanyNameParts (str
, strp
));
393 MarkWholeScreenDirty();
396 AddNewsItem
<LaunchNewsItem
> (c
, t
->index
);
400 /** Sorting weights for the company colours. */
401 static const byte _colour_sort
[COLOUR_END
] = {2, 2, 3, 2, 3, 2, 3, 2, 3, 2, 2, 2, 3, 1, 1, 1};
402 /** Similar colours, so we can try to prevent same coloured companies. */
403 static const Colours _similar_colour
[COLOUR_END
][2] = {
404 { COLOUR_BLUE
, COLOUR_LIGHT_BLUE
}, // COLOUR_DARK_BLUE
405 { COLOUR_GREEN
, COLOUR_DARK_GREEN
}, // COLOUR_PALE_GREEN
406 { INVALID_COLOUR
, INVALID_COLOUR
}, // COLOUR_PINK
407 { COLOUR_ORANGE
, INVALID_COLOUR
}, // COLOUR_YELLOW
408 { INVALID_COLOUR
, INVALID_COLOUR
}, // COLOUR_RED
409 { COLOUR_DARK_BLUE
, COLOUR_BLUE
}, // COLOUR_LIGHT_BLUE
410 { COLOUR_PALE_GREEN
, COLOUR_DARK_GREEN
}, // COLOUR_GREEN
411 { COLOUR_PALE_GREEN
, COLOUR_GREEN
}, // COLOUR_DARK_GREEN
412 { COLOUR_DARK_BLUE
, COLOUR_LIGHT_BLUE
}, // COLOUR_BLUE
413 { COLOUR_BROWN
, COLOUR_ORANGE
}, // COLOUR_CREAM
414 { COLOUR_PURPLE
, INVALID_COLOUR
}, // COLOUR_MAUVE
415 { COLOUR_MAUVE
, INVALID_COLOUR
}, // COLOUR_PURPLE
416 { COLOUR_YELLOW
, COLOUR_CREAM
}, // COLOUR_ORANGE
417 { COLOUR_CREAM
, INVALID_COLOUR
}, // COLOUR_BROWN
418 { COLOUR_WHITE
, INVALID_COLOUR
}, // COLOUR_GREY
419 { COLOUR_GREY
, INVALID_COLOUR
}, // COLOUR_WHITE
423 * Generate a company colour.
424 * @return Generated company colour.
426 static Colours
GenerateCompanyColour()
428 Colours colours
[COLOUR_END
];
430 /* Initialize array */
431 for (uint i
= 0; i
< COLOUR_END
; i
++) colours
[i
] = (Colours
)i
;
433 /* And randomize it */
434 for (uint i
= 0; i
< 100; i
++) {
436 Swap(colours
[GB(r
, 0, 4)], colours
[GB(r
, 4, 4)]);
439 /* Bubble sort it according to the values in table 1 */
440 for (uint i
= 0; i
< COLOUR_END
; i
++) {
441 for (uint j
= 1; j
< COLOUR_END
; j
++) {
442 if (_colour_sort
[colours
[j
- 1]] < _colour_sort
[colours
[j
]]) {
443 Swap(colours
[j
- 1], colours
[j
]);
448 /* Move the colours that look similar to each company's colour to the side */
450 FOR_ALL_COMPANIES(c
) {
451 Colours pcolour
= (Colours
)c
->colour
;
453 for (uint i
= 0; i
< COLOUR_END
; i
++) {
454 if (colours
[i
] == pcolour
) {
455 colours
[i
] = INVALID_COLOUR
;
460 for (uint j
= 0; j
< 2; j
++) {
461 Colours similar
= _similar_colour
[pcolour
][j
];
462 if (similar
== INVALID_COLOUR
) break;
464 for (uint i
= 1; i
< COLOUR_END
; i
++) {
465 if (colours
[i
- 1] == similar
) Swap(colours
[i
- 1], colours
[i
]);
470 /* Return the first available colour */
471 for (uint i
= 0; i
< COLOUR_END
; i
++) {
472 if (colours
[i
] != INVALID_COLOUR
) return colours
[i
];
479 * Generate a random president name of a company.
480 * @param c Company that needs a new president name.
482 static void GeneratePresidentName(Company
*c
)
486 c
->president_name_2
= Random();
487 c
->president_name_1
= SPECSTR_PRESIDENT_NAME
;
489 /* Reserve space for extra unicode character. We need to do this to be able
490 * to detect too long president name. */
491 char buffer
[(MAX_LENGTH_PRESIDENT_NAME_CHARS
+ 1) * MAX_CHAR_LENGTH
];
492 SetDParam(0, c
->index
);
493 GetString (buffer
, STR_PRESIDENT_NAME
);
494 if (Utf8StringLength(buffer
) >= MAX_LENGTH_PRESIDENT_NAME_CHARS
) continue;
497 FOR_ALL_COMPANIES(cc
) {
499 /* Reserve extra space so even overlength president names can be compared. */
500 char buffer2
[(MAX_LENGTH_PRESIDENT_NAME_CHARS
+ 1) * MAX_CHAR_LENGTH
];
501 SetDParam(0, cc
->index
);
502 GetString (buffer2
, STR_PRESIDENT_NAME
);
503 if (strcmp(buffer2
, buffer
) == 0) goto restart
;
511 * Reset the livery schemes to the company's primary colour.
512 * This is used on loading games without livery information and on new company start up.
513 * @param c Company to reset.
515 void ResetCompanyLivery(Company
*c
)
517 for (LiveryScheme scheme
= LS_BEGIN
; scheme
< LS_END
; scheme
++) {
518 c
->livery
[scheme
].in_use
= false;
519 c
->livery
[scheme
].colour1
= c
->colour
;
520 c
->livery
[scheme
].colour2
= c
->colour
;
525 * Create a new company and sets all company variables default values
527 * @param is_ai is an AI company?
528 * @param company CompanyID to use for the new company
529 * @return the company struct
531 Company
*DoStartupNewCompany(bool is_ai
, CompanyID company
= INVALID_COMPANY
)
533 if (!Company::CanAllocateItem()) return NULL
;
535 /* we have to generate colour before this company is valid */
536 Colours colour
= GenerateCompanyColour();
539 if (company
== INVALID_COMPANY
) {
540 c
= new Company(STR_SV_UNNAMED
, is_ai
);
542 if (Company::IsValidID(company
)) return NULL
;
543 c
= new (company
) Company(STR_SV_UNNAMED
, is_ai
);
548 ResetCompanyLivery(c
);
549 _company_colours
[c
->index
] = (Colours
)c
->colour
;
551 c
->money
= c
->current_loan
= (100000ll * _economy
.inflation_prices
>> 16) / 50000 * 50000;
553 c
->share_owners
[0] = c
->share_owners
[1] = c
->share_owners
[2] = c
->share_owners
[3] = INVALID_OWNER
;
555 c
->avail_railtypes
= GetCompanyRailtypes(c
->index
);
556 c
->avail_roadtypes
= GetCompanyRoadtypes(c
->index
);
557 c
->inaugurated_year
= _cur_year
;
558 RandomCompanyManagerFaceBits(c
->face
, (GenderEthnicity
)Random(), false, false); // create a random company manager face
560 SetDefaultCompanySettings(c
->index
);
561 ClearEnginesHiddenFlagOfCompany(c
->index
);
563 GeneratePresidentName(c
);
565 SetWindowDirty(WC_GRAPH_LEGEND
, 0);
566 SetWindowClassesDirty(WC_CLIENT_LIST_POPUP
);
567 SetWindowDirty(WC_CLIENT_LIST
, 0);
568 InvalidateWindowData(WC_LINKGRAPH_LEGEND
, 0);
570 InvalidateWindowData(WC_SMALLMAP
, 0, 1);
572 if (is_ai
&& (!_networking
|| _network_server
)) AI::StartNew(c
->index
);
574 AI::BroadcastNewEvent(new ScriptEventCompanyNew(c
->index
), c
->index
);
575 Game::NewEvent(new ScriptEventCompanyNew(c
->index
));
580 /** Start the next competitor now. */
581 void StartupCompanies()
583 _next_competitor_start
= 0;
586 /** Start a new competitor company if possible. */
587 static void MaybeStartNewCompany()
589 #ifdef ENABLE_NETWORK
590 if (_networking
&& Company::GetNumItems() >= _settings_client
.network
.max_companies
) return;
591 #endif /* ENABLE_NETWORK */
595 /* count number of competitors */
597 FOR_ALL_COMPANIES(c
) {
601 if (n
< (uint
)_settings_game
.difficulty
.max_no_competitors
) {
602 /* Send a command to all clients to start up a new AI.
603 * Works fine for Multiplayer and Singleplayer */
604 DoCommandP(0, 1 | INVALID_COMPANY
<< 16, 0, CMD_COMPANY_CTRL
);
608 /** Initialize the pool of companies. */
609 void InitializeCompanies()
611 _cur_company_tick_index
= 0;
615 * May company \a cbig buy company \a csmall?
616 * @param cbig Company buying \a csmall.
617 * @param csmall Company getting bought.
618 * @return Return \c true if it is allowed.
620 bool MayCompanyTakeOver(CompanyID cbig
, CompanyID csmall
)
622 const Company
*c1
= Company::Get(cbig
);
623 const Company
*c2
= Company::Get(csmall
);
625 /* Do the combined vehicle counts stay within the limits? */
626 return c1
->group_all
[VEH_TRAIN
].num_vehicle
+ c2
->group_all
[VEH_TRAIN
].num_vehicle
<= _settings_game
.vehicle
.max_trains
&&
627 c1
->group_all
[VEH_ROAD
].num_vehicle
+ c2
->group_all
[VEH_ROAD
].num_vehicle
<= _settings_game
.vehicle
.max_roadveh
&&
628 c1
->group_all
[VEH_SHIP
].num_vehicle
+ c2
->group_all
[VEH_SHIP
].num_vehicle
<= _settings_game
.vehicle
.max_ships
&&
629 c1
->group_all
[VEH_AIRCRAFT
].num_vehicle
+ c2
->group_all
[VEH_AIRCRAFT
].num_vehicle
<= _settings_game
.vehicle
.max_aircraft
;
633 * Handle the bankruptcy take over of a company.
634 * Companies going bankrupt will ask the other companies in order of their
635 * performance rating, so better performing companies get the 'do you want to
636 * merge with Y' question earlier. The question will then stay till either the
637 * company has gone bankrupt or got merged with a company.
639 * @param c the company that is going bankrupt.
641 static void HandleBankruptcyTakeover(Company
*c
)
643 /* Amount of time out for each company to take over a company;
644 * Timeout is a quarter (3 months of 30 days) divided over the
645 * number of companies. The minimum number of days in a quarter
646 * is 90: 31 in January, 28 in February and 31 in March.
647 * Note that the company going bankrupt can't buy itself. */
648 static const int TAKE_OVER_TIMEOUT
= 3 * 30 * DAY_TICKS
/ (MAX_COMPANIES
- 1);
650 assert(c
->bankrupt_asked
!= 0);
652 /* We're currently asking some company to buy 'us' */
653 if (c
->bankrupt_timeout
!= 0) {
654 c
->bankrupt_timeout
-= MAX_COMPANIES
;
655 if (c
->bankrupt_timeout
> 0) return;
656 c
->bankrupt_timeout
= 0;
661 /* Did we ask everyone for bankruptcy? If so, bail out. */
662 if (c
->bankrupt_asked
== MAX_UVALUE(CompanyMask
)) return;
664 Company
*c2
, *best
= NULL
;
665 int32 best_performance
= -1;
667 /* Ask the company with the highest performance history first */
668 FOR_ALL_COMPANIES(c2
) {
669 if (c2
->bankrupt_asked
== 0 && // Don't ask companies going bankrupt themselves
670 !HasBit(c
->bankrupt_asked
, c2
->index
) &&
671 best_performance
< c2
->old_economy
[1].performance_history
&&
672 MayCompanyTakeOver(c2
->index
, c
->index
)) {
673 best_performance
= c2
->old_economy
[1].performance_history
;
678 /* Asked all companies? */
679 if (best_performance
== -1) {
680 c
->bankrupt_asked
= MAX_UVALUE(CompanyMask
);
684 SetBit(c
->bankrupt_asked
, best
->index
);
686 c
->bankrupt_timeout
= TAKE_OVER_TIMEOUT
;
688 AI::NewEvent(best
->index
, new ScriptEventCompanyAskMerger(c
->index
, ClampToI32(c
->bankrupt_value
)));
689 } else if (IsInteractiveCompany(best
->index
)) {
690 ShowBuyCompanyDialog(c
->index
);
694 /** Called every tick for updating some company info. */
695 void OnTick_Companies()
697 if (_game_mode
== GM_EDITOR
) return;
699 Company
*c
= Company::GetIfValid(_cur_company_tick_index
);
701 if (c
->name_1
!= 0) GenerateCompanyName(c
);
702 if (c
->bankrupt_asked
!= 0) HandleBankruptcyTakeover(c
);
705 if (_next_competitor_start
== 0) {
706 _next_competitor_start
= AI::GetStartNextTime() * DAY_TICKS
;
709 if (AI::CanStartNew() && _game_mode
!= GM_MENU
&& --_next_competitor_start
== 0) {
710 MaybeStartNewCompany();
713 _cur_company_tick_index
= (_cur_company_tick_index
+ 1) % MAX_COMPANIES
;
717 * A year has passed, update the economic data of all companies, and perhaps show the
718 * financial overview window of the local company.
720 void CompaniesYearlyLoop()
724 /* Copy statistics */
725 FOR_ALL_COMPANIES(c
) {
726 memmove(&c
->yearly_expenses
[1], &c
->yearly_expenses
[0], sizeof(c
->yearly_expenses
) - sizeof(c
->yearly_expenses
[0]));
727 memset(&c
->yearly_expenses
[0], 0, sizeof(c
->yearly_expenses
[0]));
728 SetWindowDirty(WC_FINANCES
, c
->index
);
731 if (_settings_client
.gui
.show_finances
&& _local_company
!= COMPANY_SPECTATOR
) {
732 ShowCompanyFinances(_local_company
);
733 c
= Company::Get(_local_company
);
734 if (c
->num_valid_stat_ent
> 5 && c
->old_economy
[0].performance_history
< c
->old_economy
[4].performance_history
) {
735 if (_settings_client
.sound
.new_year
) SndPlayFx(SND_01_BAD_YEAR
);
737 if (_settings_client
.sound
.new_year
) SndPlayFx(SND_00_GOOD_YEAR
);
743 * Called whenever company related information changes in order to notify admins.
744 * @param company The company data changed of.
746 void CompanyAdminUpdate(const Company
*company
)
748 #ifdef ENABLE_NETWORK
749 if (_network_server
) NetworkAdminCompanyUpdate(company
);
750 #endif /* ENABLE_NETWORK */
754 * Called whenever a company is removed in order to notify admins.
755 * @param company_id The company that was removed.
756 * @param reason The reason the company was removed.
758 void CompanyAdminRemove(CompanyID company_id
, CompanyRemoveReason reason
)
760 #ifdef ENABLE_NETWORK
761 if (_network_server
) NetworkAdminCompanyRemove(company_id
, (AdminCompanyRemoveReason
)reason
);
762 #endif /* ENABLE_NETWORK */
766 * Control the companies: add, delete, etc.
768 * @param flags operation to perform
769 * @param p1 various functionality
771 * = 0 - create a new company
772 * = 1 - create a new AI company
773 * = 2 - delete a company
774 * - bits 16..24: CompanyID
777 * @return the cost of this operation or an error
779 CommandCost
CmdCompanyCtrl(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
781 InvalidateWindowData(WC_COMPANY_LEAGUE
, 0, 0);
782 CompanyID company_id
= (CompanyID
)GB(p1
, 16, 8);
783 #ifdef ENABLE_NETWORK
784 ClientID client_id
= (ClientID
)p2
;
785 #endif /* ENABLE_NETWORK */
787 switch (GB(p1
, 0, 16)) {
788 case 0: { // Create a new company
789 /* This command is only executed in a multiplayer game */
790 if (!_networking
) return CMD_ERROR
;
792 #ifdef ENABLE_NETWORK
793 /* Has the network client a correct ClientIndex? */
794 if (!(flags
& DC_EXEC
)) return CommandCost();
795 NetworkClientInfo
*ci
= NetworkClientInfo::GetByClientID(client_id
);
796 #ifndef DEBUG_DUMP_COMMANDS
797 /* When replaying the client ID is not a valid client; there
798 * are actually no clients at all. However, the company has to
799 * be created, otherwise we cannot rerun the game properly.
800 * So only allow a NULL client info in that case. */
801 if (ci
== NULL
) return CommandCost();
802 #endif /* NOT DEBUG_DUMP_COMMANDS */
804 /* Delete multiplayer progress bar */
805 DeleteWindowById(WC_NETWORK_STATUS_WINDOW
, WN_NETWORK_STATUS_WINDOW_JOIN
);
807 Company
*c
= DoStartupNewCompany(false);
809 /* A new company could not be created, revert to being a spectator */
811 if (_network_server
) {
812 ci
->client_playas
= COMPANY_SPECTATOR
;
813 NetworkUpdateClientInfo(ci
->client_id
);
818 /* This is the client (or non-dedicated server) who wants a new company */
819 if (client_id
== _network_own_client_id
) {
820 assert(_local_company
== COMPANY_SPECTATOR
);
821 SetLocalCompany(c
->index
);
822 if (!StrEmpty(_settings_client
.network
.default_company_pass
)) {
823 NetworkChangeCompanyPassword(_local_company
, _settings_client
.network
.default_company_pass
);
826 /* Now that we have a new company, broadcast our company settings to
827 * all clients so everything is in sync */
828 SyncCompanySettings();
830 MarkWholeScreenDirty();
833 NetworkServerNewCompany(c
, ci
);
834 #endif /* ENABLE_NETWORK */
838 case 1: { // Make a new AI company
839 if (!(flags
& DC_EXEC
)) return CommandCost();
841 if (company_id
!= INVALID_COMPANY
&& (company_id
>= MAX_COMPANIES
|| Company::IsValidID(company_id
))) return CMD_ERROR
;
842 Company
*c
= DoStartupNewCompany(true, company_id
);
843 #ifdef ENABLE_NETWORK
844 if (c
!= NULL
) NetworkServerNewCompany(c
, NULL
);
845 #endif /* ENABLE_NETWORK */
849 case 2: { // Delete a company
850 CompanyRemoveReason reason
= (CompanyRemoveReason
)GB(p2
, 0, 2);
851 if (reason
>= CRR_END
) return CMD_ERROR
;
853 Company
*c
= Company::GetIfValid(company_id
);
854 if (c
== NULL
) return CMD_ERROR
;
856 if (!(flags
& DC_EXEC
)) return CommandCost();
858 /* Delete any open window of the company */
859 DeleteCompanyWindows(c
->index
);
861 /* Show the bankrupt news */
862 AddNewsItem
<CompanyNewsItem
> (STR_NEWS_COMPANY_BANKRUPT_TITLE
,
863 STR_NEWS_COMPANY_BANKRUPT_DESCRIPTION
, c
);
865 /* Remove the company */
866 ChangeOwnershipOfCompanyItems(c
->index
, INVALID_OWNER
);
867 if (c
->is_ai
) AI::Stop(c
->index
);
869 CompanyID c_index
= c
->index
;
871 AI::BroadcastNewEvent(new ScriptEventCompanyBankrupt(c_index
));
872 Game::NewEvent(new ScriptEventCompanyBankrupt(c_index
));
873 CompanyAdminRemove(c_index
, (CompanyRemoveReason
)reason
);
875 if (StoryPage::GetNumItems() == 0 || Goal::GetNumItems() == 0) InvalidateWindowData(WC_MAIN_TOOLBAR
, 0);
879 default: return CMD_ERROR
;
882 InvalidateWindowClassesData(WC_GAME_OPTIONS
);
883 InvalidateWindowClassesData(WC_AI_SETTINGS
);
884 InvalidateWindowClassesData(WC_AI_LIST
);
886 return CommandCost();
890 * Change the company manager's face.
892 * @param flags operation to perform
894 * @param p2 face bitmasked
896 * @return the cost of this operation or an error
898 CommandCost
CmdSetCompanyManagerFace(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
900 CompanyManagerFace cmf
= (CompanyManagerFace
)p2
;
902 if (!IsValidCompanyManagerFace(cmf
)) return CMD_ERROR
;
904 if (flags
& DC_EXEC
) {
905 Company::Get(_current_company
)->face
= cmf
;
906 MarkWholeScreenDirty();
908 return CommandCost();
912 * Change the company's company-colour
914 * @param flags operation to perform
915 * @param p1 bitstuffed:
916 * p1 bits 0-7 scheme to set
917 * p1 bits 8-9 set in use state or first/second colour
918 * @param p2 new colour for vehicles, property, etc.
920 * @return the cost of this operation or an error
922 CommandCost
CmdSetCompanyColour(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
924 Colours colour
= Extract
<Colours
, 0, 4>(p2
);
925 LiveryScheme scheme
= Extract
<LiveryScheme
, 0, 8>(p1
);
926 byte state
= GB(p1
, 8, 2);
928 if (scheme
>= LS_END
|| state
>= 3 || colour
== INVALID_COLOUR
) return CMD_ERROR
;
930 Company
*c
= Company::Get(_current_company
);
932 /* Ensure no two companies have the same primary colour */
933 if (scheme
== LS_DEFAULT
&& state
== 0) {
935 FOR_ALL_COMPANIES(cc
) {
936 if (cc
!= c
&& cc
->colour
== colour
) return CMD_ERROR
;
940 if (flags
& DC_EXEC
) {
943 c
->livery
[scheme
].colour1
= colour
;
945 /* If setting the first colour of the default scheme, adjust the
946 * original and cached company colours too. */
947 if (scheme
== LS_DEFAULT
) {
948 _company_colours
[_current_company
] = colour
;
950 CompanyAdminUpdate(c
);
955 c
->livery
[scheme
].colour2
= colour
;
959 c
->livery
[scheme
].in_use
= colour
!= 0;
961 /* Now handle setting the default scheme's in_use flag.
962 * This is different to the other schemes, as it signifies if any
963 * scheme is active at all. If this flag is not set, then no
964 * processing of vehicle types occurs at all, and only the default
965 * colours will be used. */
967 /* If enabling a scheme, set the default scheme to be in use too */
969 c
->livery
[LS_DEFAULT
].in_use
= true;
973 /* Else loop through all schemes to see if any are left enabled.
974 * If not, disable the default scheme too. */
975 c
->livery
[LS_DEFAULT
].in_use
= false;
976 for (scheme
= LS_DEFAULT
; scheme
< LS_END
; scheme
++) {
977 if (c
->livery
[scheme
].in_use
) {
978 c
->livery
[LS_DEFAULT
].in_use
= true;
987 ResetVehicleColourMap();
988 MarkWholeScreenDirty();
990 /* All graph related to companies use the company colour. */
991 InvalidateWindowData(WC_INCOME_GRAPH
, 0);
992 InvalidateWindowData(WC_OPERATING_PROFIT
, 0);
993 InvalidateWindowData(WC_DELIVERED_CARGO
, 0);
994 InvalidateWindowData(WC_PERFORMANCE_HISTORY
, 0);
995 InvalidateWindowData(WC_COMPANY_VALUE
, 0);
996 InvalidateWindowData(WC_LINKGRAPH_LEGEND
, 0);
997 /* The smallmap owner view also stores the company colours. */
999 InvalidateWindowData(WC_SMALLMAP
, 0, 1);
1001 /* Company colour data is indirectly cached. */
1003 FOR_ALL_VEHICLES(v
) {
1004 if (v
->owner
== _current_company
) v
->InvalidateNewGRFCache();
1007 extern void UpdateObjectColours(const Company
*c
);
1008 UpdateObjectColours(c
);
1010 return CommandCost();
1014 * Is the given name in use as name of a company?
1015 * @param prop Name type to search (company name or president name).
1016 * @param name Name to search.
1017 * @return \c true if the name us unique (that is, not in use), else \c false.
1019 static inline bool IsUniqueCompanyName (char * const Company::*prop
, const char *name
)
1023 FOR_ALL_COMPANIES(c
) {
1024 if (c
->*prop
!= NULL
&& strcmp (c
->*prop
, name
) == 0) return false;
1031 * Change the name of the company.
1032 * @param tile unused
1033 * @param flags operation to perform
1036 * @param text the new name or an empty string when resetting to the default
1037 * @return the cost of this operation or an error
1039 CommandCost
CmdRenameCompany(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1041 bool reset
= StrEmpty(text
);
1044 if (Utf8StringLength(text
) >= MAX_LENGTH_COMPANY_NAME_CHARS
) return CMD_ERROR
;
1045 if (!IsUniqueCompanyName (&Company::name
, text
)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE
);
1048 if (flags
& DC_EXEC
) {
1049 Company
*c
= Company::Get(_current_company
);
1051 c
->name
= reset
? NULL
: xstrdup(text
);
1052 MarkWholeScreenDirty();
1053 CompanyAdminUpdate(c
);
1056 return CommandCost();
1060 * Change the name of the president.
1061 * @param tile unused
1062 * @param flags operation to perform
1065 * @param text the new name or an empty string when resetting to the default
1066 * @return the cost of this operation or an error
1068 CommandCost
CmdRenamePresident(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1070 bool reset
= StrEmpty(text
);
1073 if (Utf8StringLength(text
) >= MAX_LENGTH_PRESIDENT_NAME_CHARS
) return CMD_ERROR
;
1074 if (!IsUniqueCompanyName (&Company::president_name
, text
)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE
);
1077 if (flags
& DC_EXEC
) {
1078 Company
*c
= Company::Get(_current_company
);
1079 free(c
->president_name
);
1082 c
->president_name
= NULL
;
1084 c
->president_name
= xstrdup(text
);
1086 if (c
->name_1
== STR_SV_UNNAMED
&& c
->name
== NULL
) {
1088 bstrfmt (buf
, "%s Transport", text
);
1089 DoCommand(0, 0, 0, DC_EXEC
, CMD_RENAME_COMPANY
, buf
);
1093 MarkWholeScreenDirty();
1094 CompanyAdminUpdate(c
);
1097 return CommandCost();
1101 * Get the service interval for the given company and vehicle type.
1102 * @param c The company, or NULL for client-default settings.
1103 * @param type The vehicle type to get the interval for.
1104 * @return The service interval.
1106 int CompanyServiceInterval(const Company
*c
, VehicleType type
)
1108 const VehicleDefaultSettings
*vds
= (c
== NULL
) ? &_settings_client
.company
.vehicle
: &c
->settings
.vehicle
;
1110 default: NOT_REACHED();
1111 case VEH_TRAIN
: return vds
->servint_trains
;
1112 case VEH_ROAD
: return vds
->servint_roadveh
;
1113 case VEH_AIRCRAFT
: return vds
->servint_aircraft
;
1114 case VEH_SHIP
: return vds
->servint_ships
;