# company_cmd.cpp

Go to the documentation of this file.

    00001 /* $Id: company_cmd.cpp 19081 2010-02-10 16:24:05Z rubidium $ */
    00002
    00003 /*
    00004  * This file is part of OpenTTD.
    00005  * 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.
    00006  * 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.
    00007  * 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/>.
    00008  */
    00009
    00012 #include "stdafx.h"
    00013 #include "engine_base.h"
    00014 #include "company_func.h"
    00015 #include "company_gui.h"
    00016 #include "town.h"
    00017 #include "news_func.h"
    00018 #include "command_func.h"
    00019 #include "network/network.h"
    00020 #include "network/network_func.h"
    00021 #include "network/network_base.h"
    00022 #include "ai/ai.hpp"
    00023 #include "company_manager_face.h"
    00024 #include "group.h"
    00025 #include "window_func.h"
    00026 #include "strings_func.h"
    00027 #include "gfx_func.h"
    00028 #include "date_func.h"
    00029 #include "sound_func.h"
    00030 #include "autoreplace_func.h"
    00031 #include "autoreplace_gui.h"
    00032 #include "rail.h"
    00033 #include "core/pool_func.hpp"
    00034 #include "settings_func.h"
    00035 #include "vehicle_base.h"
    00036 #include "vehicle_func.h"
    00037 #include "sprite.h"
    00038
    00039 #include "table/strings.h"
    00040
    00041 CompanyByte _local_company;
    00042 CompanyByte _current_company;
    00043 /* NOSAVE: can be determined from company structs */
    00044 Colours _company_colours[MAX_COMPANIES];
    00045 CompanyManagerFace _company_manager_face;
    00046 uint _next_competitor_start;
    00047 uint _cur_company_tick_index;
    00048
    00049 CompanyPool _company_pool("Company");
    00050 INSTANTIATE_POOL_METHODS(Company)
    00051
    00052 Company::Company(uint16 name_1, bool is_ai) :
    00053   name_1(name_1),
    00054   location_of_HQ(INVALID_TILE),
    00055   is_ai(is_ai)
    00056 {
    00057   for (uint j = 0; j < 4; j++) this->share_owners[j] = COMPANY_SPECTATOR;
    00058   InvalidateWindowData(WC_PERFORMANCE_DETAIL, 0, INVALID_COMPANY);
    00059 }
    00060
    00061 Company::~Company()
    00062 {
    00063   free(this->name);
    00064   free(this->president_name);
    00065   free(this->num_engines);
    00066
    00067   if (CleaningPool()) return;
    00068
    00069   DeleteCompanyWindows(this->index);
    00070 }
    00071
    00076 void Company::PostDestructor(size_t index)
    00077 {
    00078   InvalidateWindowData(WC_GRAPH_LEGEND, 0, (int)index);
    00079   InvalidateWindowData(WC_PERFORMANCE_DETAIL, 0, (int)index);
    00080   InvalidateWindowData(WC_COMPANY_LEAGUE, 0, 0);
    00081 }
    00082
    00089 void SetLocalCompany(CompanyID new_company)
    00090 {
    00091   /* company could also be COMPANY_SPECTATOR or OWNER_NONE */
    00092   assert(Company::IsValidID(new_company) || new_company == COMPANY_SPECTATOR || new_company == OWNER_NONE);
    00093
    00094 #ifdef ENABLE_NETWORK
    00095   /* Delete the chat window, if you were team chatting. */
    00096   InvalidateWindowData(WC_SEND_NETWORK_MSG, DESTTYPE_TEAM, _local_company);
    00097 #endif
    00098
    00099   _local_company = new_company;
    00100
    00101   /* Delete any construction windows... */
    00102   DeleteConstructionWindows();
    00103
    00104   /* ... and redraw the whole screen. */
    00105   MarkWholeScreenDirty();
    00106 }
    00107
    00108 uint16 GetDrawStringCompanyColour(CompanyID company)
    00109 {
    00110   /* Get the colour for DrawString-subroutines which matches the colour
    00111    * of the company */
    00112   if (!Company::IsValidID(company)) return _colour_gradient[COLOUR_WHITE][4] | IS_PALETTE_COLOUR;
    00113   return (_colour_gradient[_company_colours[company]][4]) | IS_PALETTE_COLOUR;
    00114 }
    00115
    00116 void DrawCompanyIcon(CompanyID c, int x, int y)
    00117 {
    00118   DrawSprite(SPR_COMPANY_ICON, COMPANY_SPRITE_COLOUR(c), x, y);
    00119 }
    00120
    00127 bool IsValidCompanyManagerFace(CompanyManagerFace cmf)
    00128 {
    00129   if (!AreCompanyManagerFaceBitsValid(cmf, CMFV_GEN_ETHN, GE_WM)) return false;
    00130
    00131   GenderEthnicity ge   = (GenderEthnicity)GetCompanyManagerFaceBits(cmf, CMFV_GEN_ETHN, GE_WM);
    00132   bool has_moustache   = !HasBit(ge, GENDER_FEMALE) && GetCompanyManagerFaceBits(cmf, CMFV_HAS_MOUSTACHE,   ge) != 0;
    00133   bool has_tie_earring = !HasBit(ge, GENDER_FEMALE) || GetCompanyManagerFaceBits(cmf, CMFV_HAS_TIE_EARRING, ge) != 0;
    00134   bool has_glasses     = GetCompanyManagerFaceBits(cmf, CMFV_HAS_GLASSES, ge) != 0;
    00135
    00136   if (!AreCompanyManagerFaceBitsValid(cmf, CMFV_EYE_COLOUR, ge)) return false;
    00137   for (CompanyManagerFaceVariable cmfv = CMFV_CHEEKS; cmfv < CMFV_END; cmfv++) {
    00138     switch (cmfv) {
    00139       case CMFV_MOUSTACHE:   if (!has_moustache)   continue; break;
    00140       case CMFV_LIPS:        // FALL THROUGH
    00141       case CMFV_NOSE:        if (has_moustache)    continue; break;
    00142       case CMFV_TIE_EARRING: if (!has_tie_earring) continue; break;
    00143       case CMFV_GLASSES:     if (!has_glasses)     continue; break;
    00144       default: break;
    00145     }
    00146     if (!AreCompanyManagerFaceBitsValid(cmf, cmfv, ge)) return false;
    00147   }
    00148
    00149   return true;
    00150 }
    00151
    00152 void InvalidateCompanyWindows(const Company *company)
    00153 {
    00154   CompanyID cid = company->index;
    00155
    00156   if (cid == _local_company) SetWindowDirty(WC_STATUS_BAR, 0);
    00157   SetWindowDirty(WC_FINANCES, cid);
    00158 }
    00159
    00160 bool CheckCompanyHasMoney(CommandCost &cost)
    00161 {
    00162   if (cost.GetCost() > 0) {
    00163     const Company *c = Company::GetIfValid(_current_company);
    00164     if (c != NULL && cost.GetCost() > c->money) {
    00165       SetDParam(0, cost.GetCost());
    00166       cost.MakeError(STR_ERROR_NOT_ENOUGH_CASH_REQUIRES_CURRENCY);
    00167       return false;
    00168     }
    00169   }
    00170   return true;
    00171 }
    00172
    00173 static void SubtractMoneyFromAnyCompany(Company *c, CommandCost cost)
    00174 {
    00175   if (cost.GetCost() == 0) return;
    00176   assert(cost.GetExpensesType() != INVALID_EXPENSES);
    00177
    00178   c->money -= cost.GetCost();
    00179   c->yearly_expenses[0][cost.GetExpensesType()] += cost.GetCost();
    00180
    00181   if (HasBit(1 << EXPENSES_TRAIN_INC    |
    00182              1 << EXPENSES_ROADVEH_INC  |
    00183              1 << EXPENSES_AIRCRAFT_INC |
    00184              1 << EXPENSES_SHIP_INC, cost.GetExpensesType())) {
    00185     c->cur_economy.income -= cost.GetCost();
    00186   } else if (HasBit(1 << EXPENSES_TRAIN_RUN    |
    00187                     1 << EXPENSES_ROADVEH_RUN  |
    00188                     1 << EXPENSES_AIRCRAFT_RUN |
    00189                     1 << EXPENSES_SHIP_RUN     |
    00190                     1 << EXPENSES_PROPERTY     |
    00191                     1 << EXPENSES_LOAN_INT, cost.GetExpensesType())) {
    00192     c->cur_economy.expenses -= cost.GetCost();
    00193   }
    00194
    00195   InvalidateCompanyWindows(c);
    00196 }
    00197
    00198 void SubtractMoneyFromCompany(CommandCost cost)
    00199 {
    00200   Company *c = Company::GetIfValid(_current_company);
    00201   if (c != NULL) SubtractMoneyFromAnyCompany(c, cost);
    00202 }
    00203
    00204 void SubtractMoneyFromCompanyFract(CompanyID company, CommandCost cst)
    00205 {
    00206   Company *c = Company::Get(company);
    00207   byte m = c->money_fraction;
    00208   Money cost = cst.GetCost();
    00209
    00210   c->money_fraction = m - (byte)cost;
    00211   cost >>= 8;
    00212   if (c->money_fraction > m) cost++;
    00213   if (cost != 0) SubtractMoneyFromAnyCompany(c, CommandCost(cst.GetExpensesType(), cost));
    00214 }
    00215
    00222 void GetNameOfOwner(Owner owner, TileIndex tile)
    00223 {
    00224   SetDParam(2, owner);
    00225
    00226   if (owner != OWNER_TOWN) {
    00227     if (!Company::IsValidID(owner)) {
    00228       SetDParam(0, STR_COMPANY_SOMEONE);
    00229     } else {
    00230       SetDParam(0, STR_COMPANY_NAME);
    00231       SetDParam(1, owner);
    00232     }
    00233   } else {
    00234     assert(tile != 0);
    00235     const Town *t = ClosestTownFromTile(tile, UINT_MAX);
    00236
    00237     SetDParam(0, STR_TOWN_NAME);
    00238     SetDParam(1, t->index);
    00239   }
    00240 }
    00241
    00242
    00251 bool CheckOwnership(Owner owner, TileIndex tile)
    00252 {
    00253   assert(owner < OWNER_END);
    00254   assert(owner != OWNER_TOWN || tile != 0);
    00255
    00256   if (owner == _current_company) return true;
    00257   _error_message = STR_ERROR_OWNED_BY;
    00258   GetNameOfOwner(owner, tile);
    00259   return false;
    00260 }
    00261
    00269 bool CheckTileOwnership(TileIndex tile)
    00270 {
    00271   Owner owner = GetTileOwner(tile);
    00272
    00273   assert(owner < OWNER_END);
    00274
    00275   if (owner == _current_company) return true;
    00276   _error_message = STR_ERROR_OWNED_BY;
    00277
    00278   /* no need to get the name of the owner unless we're the local company (saves some time) */
    00279   if (IsLocalCompany()) GetNameOfOwner(owner, tile);
    00280   return false;
    00281 }
    00282
    00283 static void GenerateCompanyName(Company *c)
    00284 {
    00285   TileIndex tile;
    00286   Town *t;
    00287   StringID str;
    00288   Company *cc;
    00289   uint32 strp;
    00290   /* Reserve space for extra unicode character. We need to do this to be able
    00291    * to detect too long company name. */
    00292   char buffer[MAX_LENGTH_COMPANY_NAME_BYTES + MAX_CHAR_LENGTH];
    00293
    00294   if (c->name_1 != STR_SV_UNNAMED) return;
    00295
    00296   tile = c->last_build_coordinate;
    00297   if (tile == 0) return;
    00298
    00299   t = ClosestTownFromTile(tile, UINT_MAX);
    00300
    00301   if (t->name == NULL && IsInsideMM(t->townnametype, SPECSTR_TOWNNAME_START, SPECSTR_TOWNNAME_LAST + 1)) {
    00302     str = t->townnametype - SPECSTR_TOWNNAME_START + SPECSTR_PLAYERNAME_START;
    00303     strp = t->townnameparts;
    00304
    00305 verify_name:;
    00306     /* No companies must have this name already */
    00307     FOR_ALL_COMPANIES(cc) {
    00308       if (cc->name_1 == str && cc->name_2 == strp) goto bad_town_name;
    00309     }
    00310
    00311     GetString(buffer, str, lastof(buffer));
    00312     if (strlen(buffer) >= MAX_LENGTH_COMPANY_NAME_BYTES) goto bad_town_name;
    00313
    00314 set_name:;
    00315     c->name_1 = str;
    00316     c->name_2 = strp;
    00317
    00318     MarkWholeScreenDirty();
    00319
    00320     if (c->is_ai) {
    00321       CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
    00322       cni->FillData(c);
    00323       SetDParam(0, STR_NEWS_COMPANY_LAUNCH_TITLE);
    00324       SetDParam(1, STR_NEWS_COMPANY_LAUNCH_DESCRIPTION);
    00325       SetDParamStr(2, cni->company_name);
    00326       SetDParam(3, t->index);
    00327       AddNewsItem(STR_MESSAGE_NEWS_FORMAT, NS_COMPANY_NEW, NR_TILE, c->last_build_coordinate, NR_NONE, UINT32_MAX, cni);
    00328     }
    00329     AI::BroadcastNewEvent(new AIEventCompanyNew(c->index), c->index);
    00330     return;
    00331   }
    00332 bad_town_name:;
    00333
    00334   if (c->president_name_1 == SPECSTR_PRESIDENT_NAME) {
    00335     str = SPECSTR_ANDCO_NAME;
    00336     strp = c->president_name_2;
    00337     goto set_name;
    00338   } else {
    00339     str = SPECSTR_ANDCO_NAME;
    00340     strp = Random();
    00341     goto verify_name;
    00342   }
    00343 }
    00344
    00345 static const byte _colour_sort[COLOUR_END] = {2, 2, 3, 2, 3, 2, 3, 2, 3, 2, 2, 2, 3, 1, 1, 1};
    00346 static const Colours _similar_colour[COLOUR_END][2] = {
    00347   { COLOUR_BLUE,       COLOUR_LIGHT_BLUE }, // COLOUR_DARK_BLUE
    00348   { COLOUR_GREEN,      COLOUR_DARK_GREEN }, // COLOUR_PALE_GREEN
    00349   { INVALID_COLOUR,    INVALID_COLOUR    }, // COLOUR_PINK
    00350   { COLOUR_ORANGE,     INVALID_COLOUR    }, // COLOUR_YELLOW
    00351   { INVALID_COLOUR,    INVALID_COLOUR    }, // COLOUR_RED
    00352   { COLOUR_DARK_BLUE,  COLOUR_BLUE       }, // COLOUR_LIGHT_BLUE
    00353   { COLOUR_PALE_GREEN, COLOUR_DARK_GREEN }, // COLOUR_GREEN
    00354   { COLOUR_PALE_GREEN, COLOUR_GREEN      }, // COLOUR_DARK_GREEN
    00355   { COLOUR_DARK_BLUE,  COLOUR_LIGHT_BLUE }, // COLOUR_BLUE
    00356   { COLOUR_BROWN,      COLOUR_ORANGE     }, // COLOUR_CREAM
    00357   { COLOUR_PURPLE,     INVALID_COLOUR    }, // COLOUR_MAUVE
    00358   { COLOUR_MAUVE,      INVALID_COLOUR    }, // COLOUR_PURPLE
    00359   { COLOUR_YELLOW,     COLOUR_CREAM      }, // COLOUR_ORANGE
    00360   { COLOUR_CREAM,      INVALID_COLOUR    }, // COLOUR_BROWN
    00361   { COLOUR_WHITE,      INVALID_COLOUR    }, // COLOUR_GREY
    00362   { COLOUR_GREY,       INVALID_COLOUR    }, // COLOUR_WHITE
    00363 };
    00364
    00365 static Colours GenerateCompanyColour()
    00366 {
    00367   Colours colours[COLOUR_END];
    00368
    00369   /* Initialize array */
    00370   for (uint i = 0; i < COLOUR_END; i++) colours[i] = (Colours)i;
    00371
    00372   /* And randomize it */
    00373   for (uint i = 0; i < 100; i++) {
    00374     uint r = Random();
    00375     Swap(colours[GB(r, 0, 4)], colours[GB(r, 4, 4)]);
    00376   }
    00377
    00378   /* Bubble sort it according to the values in table 1 */
    00379   for (uint i = 0; i < COLOUR_END; i++) {
    00380     for (uint j = 1; j < COLOUR_END; j++) {
    00381       if (_colour_sort[colours[j - 1]] < _colour_sort[colours[j]]) {
    00382         Swap(colours[j - 1], colours[j]);
    00383       }
    00384     }
    00385   };
    00386
    00387   /* Move the colours that look similar to each company's colour to the side */
    00388   Company *c;
    00389   FOR_ALL_COMPANIES(c) {
    00390     Colours pcolour = (Colours)c->colour;
    00391
    00392     for (uint i = 0; i < COLOUR_END; i++) {
    00393       if (colours[i] == pcolour) {
    00394         colours[i] = INVALID_COLOUR;
    00395         break;
    00396       }
    00397     }
    00398
    00399     for (uint j = 0; j < 2; j++) {
    00400       Colours similar = _similar_colour[pcolour][j];
    00401       if (similar == INVALID_COLOUR) break;
    00402
    00403       for (uint i = 1; i < COLOUR_END; i++) {
    00404         if (colours[i - 1] == similar) Swap(colours[i - 1], colours[i]);
    00405       }
    00406     }
    00407   }
    00408
    00409   /* Return the first available colour */
    00410   for (uint i = 0; i < COLOUR_END; i++) {
    00411     if (colours[i] != INVALID_COLOUR) return colours[i];
    00412   }
    00413
    00414   NOT_REACHED();
    00415 }
    00416
    00417 static void GeneratePresidentName(Company *c)
    00418 {
    00419   for (;;) {
    00420 restart:;
    00421     c->president_name_2 = Random();
    00422     c->president_name_1 = SPECSTR_PRESIDENT_NAME;
    00423
    00424     /* Reserve space for extra unicode character. We need to do this to be able
    00425      * to detect too long president name. */
    00426     char buffer[MAX_LENGTH_PRESIDENT_NAME_BYTES + MAX_CHAR_LENGTH];
    00427     SetDParam(0, c->index);
    00428     GetString(buffer, STR_PRESIDENT_NAME, lastof(buffer));
    00429     if (strlen(buffer) >= MAX_LENGTH_PRESIDENT_NAME_BYTES) continue;
    00430
    00431     Company *cc;
    00432     FOR_ALL_COMPANIES(cc) {
    00433       if (c != cc) {
    00434         /* Reserve extra space so even overlength president names can be compared. */
    00435         char buffer2[MAX_LENGTH_PRESIDENT_NAME_BYTES + MAX_CHAR_LENGTH];
    00436         SetDParam(0, cc->index);
    00437         GetString(buffer2, STR_PRESIDENT_NAME, lastof(buffer2));
    00438         if (strcmp(buffer2, buffer) == 0) goto restart;
    00439       }
    00440     }
    00441     return;
    00442   }
    00443 }
    00444
    00445 void ResetCompanyLivery(Company *c)
    00446 {
    00447   for (LiveryScheme scheme = LS_BEGIN; scheme < LS_END; scheme++) {
    00448     c->livery[scheme].in_use  = false;
    00449     c->livery[scheme].colour1 = c->colour;
    00450     c->livery[scheme].colour2 = c->colour;
    00451   }
    00452 }
    00453
    00461 Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY)
    00462 {
    00463   if (!Company::CanAllocateItem()) return NULL;
    00464
    00465   /* we have to generate colour before this company is valid */
    00466   Colours colour = GenerateCompanyColour();
    00467
    00468   Company *c;
    00469   if (company == INVALID_COMPANY) {
    00470     c = new Company(STR_SV_UNNAMED, is_ai);
    00471   } else {
    00472     if (Company::IsValidID(company)) return NULL;
    00473     c = new (company) Company(STR_SV_UNNAMED, is_ai);
    00474   }
    00475
    00476   c->colour = colour;
    00477
    00478   ResetCompanyLivery(c);
    00479   _company_colours[c->index] = (Colours)c->colour;
    00480
    00481   c->money = c->current_loan = 100000;
    00482
    00483   c->share_owners[0] = c->share_owners[1] = c->share_owners[2] = c->share_owners[3] = INVALID_OWNER;
    00484
    00485   c->avail_railtypes = GetCompanyRailtypes(c->index);
    00486   c->avail_roadtypes = GetCompanyRoadtypes(c->index);
    00487   c->inaugurated_year = _cur_year;
    00488   RandomCompanyManagerFaceBits(c->face, (GenderEthnicity)Random(), false); // create a random company manager face
    00489
    00490   SetDefaultCompanySettings(c->index);
    00491
    00492   GeneratePresidentName(c);
    00493
    00494   SetWindowDirty(WC_GRAPH_LEGEND, 0);
    00495   SetWindowDirty(WC_TOOLBAR_MENU, 0);
    00496   SetWindowDirty(WC_CLIENT_LIST, 0);
    00497
    00498   if (is_ai && (!_networking || _network_server)) AI::StartNew(c->index);
    00499
    00500   c->num_engines = CallocT<uint16>(Engine::GetPoolSize());
    00501
    00502   return c;
    00503 }
    00504
    00505 void StartupCompanies()
    00506 {
    00507   _next_competitor_start = 0;
    00508 }
    00509
    00510 #ifdef ENABLE_AI
    00511 static void MaybeStartNewCompany()
    00512 {
    00513 #ifdef ENABLE_NETWORK
    00514   if (_networking && Company::GetNumItems() >= _settings_client.network.max_companies) return;
    00515 #endif /* ENABLE_NETWORK */
    00516
    00517   Company *c;
    00518
    00519   /* count number of competitors */
    00520   uint n = 0;
    00521   FOR_ALL_COMPANIES(c) {
    00522     if (c->is_ai) n++;
    00523   }
    00524
    00525   if (n < (uint)_settings_game.difficulty.max_no_competitors) {
    00526     /* Send a command to all clients to start up a new AI.
    00527      * Works fine for Multiplayer and Singleplayer */
    00528     DoCommandP(0, 1, INVALID_COMPANY, CMD_COMPANY_CTRL);
    00529   }
    00530 }
    00531 #endif /* ENABLE_AI */
    00532
    00533 void InitializeCompanies()
    00534 {
    00535   _company_pool.CleanPool();
    00536   _cur_company_tick_index = 0;
    00537 }
    00538
    00548 static void HandleBankruptcyTakeover(Company *c)
    00549 {
    00550   /* Amount of time out for each company to take over a company;
    00551    * Timeout is a quarter (3 months of 30 days) divided over the
    00552    * number of companies. The minimum number of days in a quarter
    00553    * is 90: 31 in January, 28 in February and 31 in March.
    00554    * Note that the company going bankrupt can't buy itself. */
    00555   static const int TAKE_OVER_TIMEOUT = 3 * 30 * DAY_TICKS / (MAX_COMPANIES - 1);
    00556
    00557   assert(c->bankrupt_asked != 0);
    00558
    00559   /* We're currently asking some company to buy 'us' */
    00560   if (c->bankrupt_timeout != 0) {
    00561     c->bankrupt_timeout -= MAX_COMPANIES;
    00562     if (c->bankrupt_timeout > 0) return;
    00563     c->bankrupt_timeout = 0;
    00564
    00565     return;
    00566   }
    00567
    00568   /* Did we ask everyone for bankruptcy? If so, bail out. */
    00569   if (c->bankrupt_asked == MAX_UVALUE(CompanyMask)) return;
    00570
    00571   Company *c2, *best = NULL;
    00572   int32 best_performance = -1;
    00573
    00574   /* Ask the company with the highest performance history first */
    00575   FOR_ALL_COMPANIES(c2) {
    00576     if (c2->bankrupt_asked == 0 && // Don't ask companies going bankrupt themselves
    00577         !HasBit(c->bankrupt_asked, c2->index) &&
    00578         best_performance < c2->old_economy[1].performance_history) {
    00579       best_performance = c2->old_economy[1].performance_history;
    00580       best = c2;
    00581     }
    00582   }
    00583
    00584   /* Asked all companies? */
    00585   if (best_performance == -1) {
    00586     c->bankrupt_asked = MAX_UVALUE(CompanyMask);
    00587     return;
    00588   }
    00589
    00590   SetBit(c->bankrupt_asked, best->index);
    00591
    00592   if (IsInteractiveCompany(best->index)) {
    00593     c->bankrupt_timeout = TAKE_OVER_TIMEOUT;
    00594     ShowBuyCompanyDialog(c->index);
    00595     return;
    00596   }
    00597
    00598   if (best->is_ai) {
    00599     AI::NewEvent(best->index, new AIEventCompanyAskMerger(c->index, ClampToI32(c->bankrupt_value)));
    00600   }
    00601 }
    00602
    00603 void OnTick_Companies()
    00604 {
    00605   if (_game_mode == GM_EDITOR) return;
    00606
    00607   Company *c = Company::GetIfValid(_cur_company_tick_index);
    00608   if (c != NULL) {
    00609     if (c->name_1 != 0) GenerateCompanyName(c);
    00610     if (c->bankrupt_asked != 0) HandleBankruptcyTakeover(c);
    00611   }
    00612
    00613 #ifdef ENABLE_AI
    00614   if (_next_competitor_start == 0) {
    00615     _next_competitor_start = AI::GetStartNextTime() * DAY_TICKS;
    00616   }
    00617
    00618   if (AI::CanStartNew() && _game_mode != GM_MENU && --_next_competitor_start == 0) {
    00619     MaybeStartNewCompany();
    00620   }
    00621 #endif /* ENABLE_AI */
    00622
    00623   _cur_company_tick_index = (_cur_company_tick_index + 1) % MAX_COMPANIES;
    00624 }
    00625
    00626 void CompaniesYearlyLoop()
    00627 {
    00628   Company *c;
    00629
    00630   /* Copy statistics */
    00631   FOR_ALL_COMPANIES(c) {
    00632     memmove(&c->yearly_expenses[1], &c->yearly_expenses[0], sizeof(c->yearly_expenses) - sizeof(c->yearly_expenses[0]));
    00633     memset(&c->yearly_expenses[0], 0, sizeof(c->yearly_expenses[0]));
    00634     SetWindowDirty(WC_FINANCES, c->index);
    00635   }
    00636
    00637   if (_settings_client.gui.show_finances && _local_company != COMPANY_SPECTATOR) {
    00638     ShowCompanyFinances(_local_company);
    00639     c = Company::Get(_local_company);
    00640     if (c->num_valid_stat_ent > 5 && c->old_economy[0].performance_history < c->old_economy[4].performance_history) {
    00641       SndPlayFx(SND_01_BAD_YEAR);
    00642     } else {
    00643       SndPlayFx(SND_00_GOOD_YEAR);
    00644     }
    00645   }
    00646 }
    00647
    00659 CommandCost CmdSetAutoReplace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00660 {
    00661   Company *c = Company::GetIfValid(_current_company);
    00662   if (c == NULL) return CMD_ERROR;
    00663
    00664   EngineID old_engine_type = GB(p2, 0, 16);
    00665   EngineID new_engine_type = GB(p2, 16, 16);
    00666   GroupID id_g = GB(p1, 16, 16);
    00667   CommandCost cost;
    00668
    00669   if (!Group::IsValidID(id_g) && !IsAllGroupID(id_g) && !IsDefaultGroupID(id_g)) return CMD_ERROR;
    00670   if (!Engine::IsValidID(old_engine_type)) return CMD_ERROR;
    00671
    00672   if (new_engine_type != INVALID_ENGINE) {
    00673     if (!Engine::IsValidID(new_engine_type)) return CMD_ERROR;
    00674     if (!CheckAutoreplaceValidity(old_engine_type, new_engine_type, _current_company)) return CMD_ERROR;
    00675
    00676     cost = AddEngineReplacementForCompany(c, old_engine_type, new_engine_type, id_g, flags);
    00677   } else {
    00678     cost = RemoveEngineReplacementForCompany(c, old_engine_type, id_g, flags);
    00679   }
    00680
    00681   if ((flags & DC_EXEC) && IsLocalCompany()) InvalidateAutoreplaceWindow(old_engine_type, id_g);
    00682
    00683   return cost;
    00684 }
    00685
    00691 void CompanyNewsInformation::FillData(const Company *c, const Company *other)
    00692 {
    00693   SetDParam(0, c->index);
    00694   GetString(this->company_name, STR_COMPANY_NAME, lastof(this->company_name));
    00695
    00696   if (other == NULL) {
    00697     *this->other_company_name = '\0';
    00698   } else {
    00699     SetDParam(0, other->index);
    00700     GetString(this->other_company_name, STR_COMPANY_NAME, lastof(this->other_company_name));
    00701     c = other;
    00702   }
    00703
    00704   SetDParam(0, c->index);
    00705   GetString(this->president_name, STR_PRESIDENT_NAME_MANAGER, lastof(this->president_name));
    00706
    00707   this->colour = c->colour;
    00708   this->face = c->face;
    00709
    00710 }
    00711
    00733 CommandCost CmdCompanyCtrl(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00734 {
    00735   if (flags & DC_EXEC) _current_company = OWNER_NONE;
    00736
    00737   InvalidateWindowData(WC_COMPANY_LEAGUE, 0, 0);
    00738
    00739   switch (p1) {
    00740     case 0: { // Create a new company
    00741       /* This command is only executed in a multiplayer game */
    00742       if (!_networking) return CMD_ERROR;
    00743
    00744 #ifdef ENABLE_NETWORK
    00745
    00746       /* Joining Client:
    00747        * _local_company: COMPANY_SPECTATOR
    00748        * cid = clientid
    00749        *
    00750        * Other client(s)/server:
    00751        * _local_company: what they play as
    00752        * cid = requested company/company of joining client */
    00753       ClientID cid = (ClientID)p2;
    00754
    00755       /* Has the network client a correct ClientIndex? */
    00756       if (!(flags & DC_EXEC)) return CommandCost();
    00757       NetworkClientInfo *ci = NetworkFindClientInfoFromClientID(cid);
    00758       if (ci == NULL) return CommandCost();
    00759
    00760       /* Delete multiplayer progress bar */
    00761       DeleteWindowById(WC_NETWORK_STATUS_WINDOW, 0);
    00762
    00763       Company *c = DoStartupNewCompany(false);
    00764
    00765       /* A new company could not be created, revert to being a spectator */
    00766       if (c == NULL) {
    00767         if (_network_server) {
    00768           ci->client_playas = COMPANY_SPECTATOR;
    00769           NetworkUpdateClientInfo(ci->client_id);
    00770         }
    00771         break;
    00772       }
    00773
    00774       /* This is the client (or non-dedicated server) who wants a new company */
    00775       if (cid == _network_own_client_id) {
    00776         assert(_local_company == COMPANY_SPECTATOR);
    00777         SetLocalCompany(c->index);
    00778         if (!StrEmpty(_settings_client.network.default_company_pass)) {
    00779           NetworkChangeCompanyPassword(_settings_client.network.default_company_pass);
    00780         }
    00781
    00782         _current_company = _local_company;
    00783
    00784         /* Now that we have a new company, broadcast our company settings to
    00785          * all clients so everything is in sync */
    00786         SyncCompanySettings();
    00787
    00788         MarkWholeScreenDirty();
    00789       }
    00790
    00791       if (_network_server) {
    00792         /* XXX - UGLY! p2 (pid) is mis-used to fetch the client-id, done at
    00793          * server side in network_server.c:838, function
    00794          * DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_COMMAND) */
    00795         CompanyID old_playas = ci->client_playas;
    00796         ci->client_playas = c->index;
    00797         NetworkUpdateClientInfo(ci->client_id);
    00798
    00799         if (Company::IsValidID(ci->client_playas)) {
    00800           _network_company_states[c->index].months_empty = 0;
    00801           _network_company_states[c->index].password[0] = '\0';
    00802           NetworkServerUpdateCompanyPassworded(ci->client_playas, false);
    00803
    00804           /* XXX - When a client joins, we automatically set its name to the
    00805            * client's name (for some reason). As it stands now only the server
    00806            * knows the client's name, so it needs to send out a "broadcast" to
    00807            * do this. To achieve this we send a network command. However, it
    00808            * uses _local_company to execute the command as.  To prevent abuse
    00809            * (eg. only yourself can change your name/company), we 'cheat' by
    00810            * impersonation _local_company as the server. Not the best solution;
    00811            * but it works.
    00812            * TODO: Perhaps this could be improved by when the client is ready
    00813            * with joining to let it send itself the command, and not the server?
    00814            * For example in network_client.c:534? */
    00815           NetworkSend_Command(0, 0, 0, CMD_RENAME_PRESIDENT, NULL, ci->client_name, ci->client_playas);
    00816         }
    00817
    00818         /* Announce new company on network, if the client was a SPECTATOR before */
    00819         if (old_playas == COMPANY_SPECTATOR) {
    00820           NetworkServerSendChat(NETWORK_ACTION_COMPANY_NEW, DESTTYPE_BROADCAST, 0, "", ci->client_id, ci->client_playas + 1);
    00821         }
    00822       }
    00823 #endif /* ENABLE_NETWORK */
    00824     } break;
    00825
    00826     case 1: // Make a new AI company
    00827       if (!(flags & DC_EXEC)) return CommandCost();
    00828
    00829       if (p2 != INVALID_COMPANY && (p2 >= MAX_COMPANIES || Company::IsValidID(p2))) return CMD_ERROR;
    00830       DoStartupNewCompany(true, (CompanyID)p2);
    00831       break;
    00832
    00833     case 2: { // Delete a company
    00834       Company *c = Company::GetIfValid(p2);
    00835       if (c == NULL) return CMD_ERROR;
    00836
    00837       if (!(flags & DC_EXEC)) return CommandCost();
    00838
    00839       /* Delete any open window of the company */
    00840       DeleteCompanyWindows(c->index);
    00841       CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
    00842       cni->FillData(c);
    00843
    00844       /* Show the bankrupt news */
    00845       SetDParam(0, STR_NEWS_COMPANY_BANKRUPT_TITLE);
    00846       SetDParam(1, STR_NEWS_COMPANY_BANKRUPT_DESCRIPTION);
    00847       SetDParamStr(2, cni->company_name);
    00848       AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, NS_COMPANY_BANKRUPT, cni);
    00849
    00850       /* Remove the company */
    00851       ChangeOwnershipOfCompanyItems(c->index, INVALID_OWNER);
    00852       if (c->is_ai) AI::Stop(c->index);
    00853
    00854       CompanyID c_index = c->index;
    00855       delete c;
    00856       AI::BroadcastNewEvent(new AIEventCompanyBankrupt(c_index));
    00857     } break;
    00858
    00859     default: return CMD_ERROR;
    00860   }
    00861
    00862   return CommandCost();
    00863 }
    00864
    00873 CommandCost CmdSetCompanyManagerFace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00874 {
    00875   CompanyManagerFace cmf = (CompanyManagerFace)p2;
    00876
    00877   if (!IsValidCompanyManagerFace(cmf)) return CMD_ERROR;
    00878
    00879   if (flags & DC_EXEC) {
    00880     Company::Get(_current_company)->face = cmf;
    00881     MarkWholeScreenDirty();
    00882   }
    00883   return CommandCost();
    00884 }
    00885
    00896 CommandCost CmdSetCompanyColour(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00897 {
    00898   if (p2 >= 16) return CMD_ERROR; // max 16 colours
    00899
    00900   Colours colour = (Colours)p2;
    00901
    00902   LiveryScheme scheme = (LiveryScheme)GB(p1, 0, 8);
    00903   byte state = GB(p1, 8, 2);
    00904
    00905   if (scheme >= LS_END || state >= 3) return CMD_ERROR;
    00906
    00907   Company *c = Company::Get(_current_company);
    00908
    00909   /* Ensure no two companies have the same primary colour */
    00910   if (scheme == LS_DEFAULT && state == 0) {
    00911     const Company *cc;
    00912     FOR_ALL_COMPANIES(cc) {
    00913       if (cc != c && cc->colour == colour) return CMD_ERROR;
    00914     }
    00915   }
    00916
    00917   if (flags & DC_EXEC) {
    00918     switch (state) {
    00919       case 0:
    00920         c->livery[scheme].colour1 = colour;
    00921
    00922         /* If setting the first colour of the default scheme, adjust the
    00923          * original and cached company colours too. */
    00924         if (scheme == LS_DEFAULT) {
    00925           _company_colours[_current_company] = colour;
    00926           c->colour = colour;
    00927         }
    00928         break;
    00929
    00930       case 1:
    00931         c->livery[scheme].colour2 = colour;
    00932         break;
    00933
    00934       case 2:
    00935         c->livery[scheme].in_use = colour != 0;
    00936
    00937         /* Now handle setting the default scheme's in_use flag.
    00938          * This is different to the other schemes, as it signifies if any
    00939          * scheme is active at all. If this flag is not set, then no
    00940          * processing of vehicle types occurs at all, and only the default
    00941          * colours will be used. */
    00942
    00943         /* If enabling a scheme, set the default scheme to be in use too */
    00944         if (colour != 0) {
    00945           c->livery[LS_DEFAULT].in_use = true;
    00946           break;
    00947         }
    00948
    00949         /* Else loop through all schemes to see if any are left enabled.
    00950          * If not, disable the default scheme too. */
    00951         c->livery[LS_DEFAULT].in_use = false;
    00952         for (scheme = LS_DEFAULT; scheme < LS_END; scheme++) {
    00953           if (c->livery[scheme].in_use) {
    00954             c->livery[LS_DEFAULT].in_use = true;
    00955             break;
    00956           }
    00957         }
    00958         break;
    00959
    00960       default:
    00961         break;
    00962     }
    00963     ResetVehicleColourMap();
    00964     MarkWholeScreenDirty();
    00965
    00966     /* Company colour data is indirectly cached. */
    00967     Vehicle *v;
    00968     FOR_ALL_VEHICLES(v) {
    00969       if (v->owner == _current_company) v->InvalidateNewGRFCache();
    00970     }
    00971   }
    00972   return CommandCost();
    00973 }
    00974
    00975 static bool IsUniqueCompanyName(const char *name)
    00976 {
    00977   const Company *c;
    00978
    00979   FOR_ALL_COMPANIES(c) {
    00980     if (c->name != NULL && strcmp(c->name, name) == 0) return false;
    00981   }
    00982
    00983   return true;
    00984 }
    00985
    00994 CommandCost CmdRenameCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00995 {
    00996   bool reset = StrEmpty(text);
    00997
    00998   if (!reset) {
    00999     if (strlen(text) >= MAX_LENGTH_COMPANY_NAME_BYTES) return CMD_ERROR;
    01000     if (!IsUniqueCompanyName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
    01001   }
    01002
    01003   if (flags & DC_EXEC) {
    01004     Company *c = Company::Get(_current_company);
    01005     free(c->name);
    01006     c->name = reset ? NULL : strdup(text);
    01007     MarkWholeScreenDirty();
    01008   }
    01009
    01010   return CommandCost();
    01011 }
    01012
    01013 static bool IsUniquePresidentName(const char *name)
    01014 {
    01015   const Company *c;
    01016
    01017   FOR_ALL_COMPANIES(c) {
    01018     if (c->president_name != NULL && strcmp(c->president_name, name) == 0) return false;
    01019   }
    01020
    01021   return true;
    01022 }
    01023
    01032 CommandCost CmdRenamePresident(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01033 {
    01034   bool reset = StrEmpty(text);
    01035
    01036   if (!reset) {
    01037     if (strlen(text) >= MAX_LENGTH_PRESIDENT_NAME_BYTES) return CMD_ERROR;
    01038     if (!IsUniquePresidentName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
    01039   }
    01040
    01041   if (flags & DC_EXEC) {
    01042     Company *c = Company::Get(_current_company);
    01043     free(c->president_name);
    01044
    01045     if (reset) {
    01046       c->president_name = NULL;
    01047     } else {
    01048       c->president_name = strdup(text);
    01049
    01050       if (c->name_1 == STR_SV_UNNAMED && c->name == NULL) {
    01051         char buf[80];
    01052
    01053         snprintf(buf, lengthof(buf), "%s Transport", text);
    01054         DoCommand(0, 0, 0, DC_EXEC, CMD_RENAME_COMPANY, buf);
    01055       }
    01056     }
    01057
    01058     MarkWholeScreenDirty();
    01059   }
    01060
    01061   return CommandCost();
    01062 }