# company_cmd.cpp

Go to the documentation of this file.

    00001 /* $Id: company_cmd.cpp 23822 2012-01-17 21:13:02Z 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 "company_base.h"
    00014 #include "company_func.h"
    00015 #include "company_gui.h"
    00016 #include "town.h"
    00017 #include "news_func.h"
    00018 #include "cmd_helper.h"
    00019 #include "command_func.h"
    00020 #include "network/network.h"
    00021 #include "network/network_func.h"
    00022 #include "network/network_base.h"
    00023 #include "network/network_admin.h"
    00024 #include "ai/ai.hpp"
    00025 #include "company_manager_face.h"
    00026 #include "window_func.h"
    00027 #include "strings_func.h"
    00028 #include "date_func.h"
    00029 #include "sound_func.h"
    00030 #include "rail.h"
    00031 #include "core/pool_func.hpp"
    00032 #include "settings_func.h"
    00033 #include "vehicle_base.h"
    00034 #include "vehicle_func.h"
    00035 #include "smallmap_gui.h"
    00036 #include "game/game.hpp"
    00037
    00038 #include "table/strings.h"
    00039
    00040 CompanyByte _local_company;
    00041 CompanyByte _current_company;
    00042 Colours _company_colours[MAX_COMPANIES];
    00043 CompanyManagerFace _company_manager_face;
    00044 uint _next_competitor_start;
    00045 uint _cur_company_tick_index;
    00046
    00047 CompanyPool _company_pool("Company");
    00048 INSTANTIATE_POOL_METHODS(Company)
    00049
    00050
    00055 Company::Company(uint16 name_1, bool is_ai)
    00056 {
    00057   this->name_1 = name_1;
    00058   this->location_of_HQ = INVALID_TILE;
    00059   this->is_ai = is_ai;
    00060   this->terraform_limit = _settings_game.construction.terraform_frame_burst << 16;
    00061   this->clear_limit     = _settings_game.construction.clear_frame_burst << 16;
    00062
    00063   for (uint j = 0; j < 4; j++) this->share_owners[j] = COMPANY_SPECTATOR;
    00064   InvalidateWindowData(WC_PERFORMANCE_DETAIL, 0, INVALID_COMPANY);
    00065 }
    00066
    00068 Company::~Company()
    00069 {
    00070   if (CleaningPool()) return;
    00071
    00072   DeleteCompanyWindows(this->index);
    00073 }
    00074
    00079 void Company::PostDestructor(size_t index)
    00080 {
    00081   InvalidateWindowData(WC_GRAPH_LEGEND, 0, (int)index);
    00082   InvalidateWindowData(WC_PERFORMANCE_DETAIL, 0, (int)index);
    00083   InvalidateWindowData(WC_COMPANY_LEAGUE, 0, 0);
    00084   /* If the currently shown error message has this company in it, then close it. */
    00085   InvalidateWindowData(WC_ERRMSG, 0);
    00086 }
    00087
    00094 void SetLocalCompany(CompanyID new_company)
    00095 {
    00096   /* company could also be COMPANY_SPECTATOR or OWNER_NONE */
    00097   assert(Company::IsValidID(new_company) || new_company == COMPANY_SPECTATOR || new_company == OWNER_NONE);
    00098
    00099 #ifdef ENABLE_NETWORK
    00100   /* Delete the chat window, if you were team chatting. */
    00101   InvalidateWindowData(WC_SEND_NETWORK_MSG, DESTTYPE_TEAM, _local_company);
    00102 #endif
    00103
    00104   assert(IsLocalCompany());
    00105
    00106   _current_company = _local_company = new_company;
    00107
    00108   /* Delete any construction windows... */
    00109   DeleteConstructionWindows();
    00110
    00111   /* ... and redraw the whole screen. */
    00112   MarkWholeScreenDirty();
    00113   InvalidateWindowClassesData(WC_SIGN_LIST, -1);
    00114 }
    00115
    00121 TextColour GetDrawStringCompanyColour(CompanyID company)
    00122 {
    00123   if (!Company::IsValidID(company)) return (TextColour)_colour_gradient[COLOUR_WHITE][4] | TC_IS_PALETTE_COLOUR;
    00124   return (TextColour)_colour_gradient[_company_colours[company]][4] | TC_IS_PALETTE_COLOUR;
    00125 }
    00126
    00133 void DrawCompanyIcon(CompanyID c, int x, int y)
    00134 {
    00135   DrawSprite(SPR_COMPANY_ICON, COMPANY_SPRITE_COLOUR(c), x, y);
    00136 }
    00137
    00144 static bool IsValidCompanyManagerFace(CompanyManagerFace cmf)
    00145 {
    00146   if (!AreCompanyManagerFaceBitsValid(cmf, CMFV_GEN_ETHN, GE_WM)) return false;
    00147
    00148   GenderEthnicity ge   = (GenderEthnicity)GetCompanyManagerFaceBits(cmf, CMFV_GEN_ETHN, GE_WM);
    00149   bool has_moustache   = !HasBit(ge, GENDER_FEMALE) && GetCompanyManagerFaceBits(cmf, CMFV_HAS_MOUSTACHE,   ge) != 0;
    00150   bool has_tie_earring = !HasBit(ge, GENDER_FEMALE) || GetCompanyManagerFaceBits(cmf, CMFV_HAS_TIE_EARRING, ge) != 0;
    00151   bool has_glasses     = GetCompanyManagerFaceBits(cmf, CMFV_HAS_GLASSES, ge) != 0;
    00152
    00153   if (!AreCompanyManagerFaceBitsValid(cmf, CMFV_EYE_COLOUR, ge)) return false;
    00154   for (CompanyManagerFaceVariable cmfv = CMFV_CHEEKS; cmfv < CMFV_END; cmfv++) {
    00155     switch (cmfv) {
    00156       case CMFV_MOUSTACHE:   if (!has_moustache)   continue; break;
    00157       case CMFV_LIPS:        // FALL THROUGH
    00158       case CMFV_NOSE:        if (has_moustache)    continue; break;
    00159       case CMFV_TIE_EARRING: if (!has_tie_earring) continue; break;
    00160       case CMFV_GLASSES:     if (!has_glasses)     continue; break;
    00161       default: break;
    00162     }
    00163     if (!AreCompanyManagerFaceBitsValid(cmf, cmfv, ge)) return false;
    00164   }
    00165
    00166   return true;
    00167 }
    00168
    00173 void InvalidateCompanyWindows(const Company *company)
    00174 {
    00175   CompanyID cid = company->index;
    00176
    00177   if (cid == _local_company) SetWindowDirty(WC_STATUS_BAR, 0);
    00178   SetWindowDirty(WC_FINANCES, cid);
    00179 }
    00180
    00186 bool CheckCompanyHasMoney(CommandCost &cost)
    00187 {
    00188   if (cost.GetCost() > 0) {
    00189     const Company *c = Company::GetIfValid(_current_company);
    00190     if (c != NULL && cost.GetCost() > c->money) {
    00191       SetDParam(0, cost.GetCost());
    00192       cost.MakeError(STR_ERROR_NOT_ENOUGH_CASH_REQUIRES_CURRENCY);
    00193       return false;
    00194     }
    00195   }
    00196   return true;
    00197 }
    00198
    00204 static void SubtractMoneyFromAnyCompany(Company *c, CommandCost cost)
    00205 {
    00206   if (cost.GetCost() == 0) return;
    00207   assert(cost.GetExpensesType() != INVALID_EXPENSES);
    00208
    00209   c->money -= cost.GetCost();
    00210   c->yearly_expenses[0][cost.GetExpensesType()] += cost.GetCost();
    00211
    00212   if (HasBit(1 << EXPENSES_TRAIN_INC    |
    00213              1 << EXPENSES_ROADVEH_INC  |
    00214              1 << EXPENSES_AIRCRAFT_INC |
    00215              1 << EXPENSES_SHIP_INC, cost.GetExpensesType())) {
    00216     c->cur_economy.income -= cost.GetCost();
    00217   } else if (HasBit(1 << EXPENSES_TRAIN_RUN    |
    00218                     1 << EXPENSES_ROADVEH_RUN  |
    00219                     1 << EXPENSES_AIRCRAFT_RUN |
    00220                     1 << EXPENSES_SHIP_RUN     |
    00221                     1 << EXPENSES_PROPERTY     |
    00222                     1 << EXPENSES_LOAN_INT, cost.GetExpensesType())) {
    00223     c->cur_economy.expenses -= cost.GetCost();
    00224   }
    00225
    00226   InvalidateCompanyWindows(c);
    00227 }
    00228
    00233 void SubtractMoneyFromCompany(CommandCost cost)
    00234 {
    00235   Company *c = Company::GetIfValid(_current_company);
    00236   if (c != NULL) SubtractMoneyFromAnyCompany(c, cost);
    00237 }
    00238
    00244 void SubtractMoneyFromCompanyFract(CompanyID company, CommandCost cst)
    00245 {
    00246   Company *c = Company::Get(company);
    00247   byte m = c->money_fraction;
    00248   Money cost = cst.GetCost();
    00249
    00250   c->money_fraction = m - (byte)cost;
    00251   cost >>= 8;
    00252   if (c->money_fraction > m) cost++;
    00253   if (cost != 0) SubtractMoneyFromAnyCompany(c, CommandCost(cst.GetExpensesType(), cost));
    00254 }
    00255
    00257 void UpdateLandscapingLimits()
    00258 {
    00259   Company *c;
    00260   FOR_ALL_COMPANIES(c) {
    00261     c->terraform_limit = min(c->terraform_limit + _settings_game.construction.terraform_per_64k_frames, (uint32)_settings_game.construction.terraform_frame_burst << 16);
    00262     c->clear_limit     = min(c->clear_limit     + _settings_game.construction.clear_per_64k_frames,     (uint32)_settings_game.construction.clear_frame_burst << 16);
    00263   }
    00264 }
    00265
    00272 void GetNameOfOwner(Owner owner, TileIndex tile)
    00273 {
    00274   SetDParam(2, owner);
    00275
    00276   if (owner != OWNER_TOWN) {
    00277     if (!Company::IsValidID(owner)) {
    00278       SetDParam(0, STR_COMPANY_SOMEONE);
    00279     } else {
    00280       SetDParam(0, STR_COMPANY_NAME);
    00281       SetDParam(1, owner);
    00282     }
    00283   } else {
    00284     assert(tile != 0);
    00285     const Town *t = ClosestTownFromTile(tile, UINT_MAX);
    00286
    00287     SetDParam(0, STR_TOWN_NAME);
    00288     SetDParam(1, t->index);
    00289   }
    00290 }
    00291
    00292
    00301 CommandCost CheckOwnership(Owner owner, TileIndex tile)
    00302 {
    00303   assert(owner < OWNER_END);
    00304   assert(owner != OWNER_TOWN || tile != 0);
    00305
    00306   if (owner == _current_company) return CommandCost();
    00307
    00308   GetNameOfOwner(owner, tile);
    00309   return_cmd_error(STR_ERROR_OWNED_BY);
    00310 }
    00311
    00319 CommandCost CheckTileOwnership(TileIndex tile)
    00320 {
    00321   Owner owner = GetTileOwner(tile);
    00322
    00323   assert(owner < OWNER_END);
    00324
    00325   if (owner == _current_company) return CommandCost();
    00326
    00327   /* no need to get the name of the owner unless we're the local company (saves some time) */
    00328   if (IsLocalCompany()) GetNameOfOwner(owner, tile);
    00329   return_cmd_error(STR_ERROR_OWNED_BY);
    00330 }
    00331
    00336 static void GenerateCompanyName(Company *c)
    00337 {
    00338   /* Reserve space for extra unicode character. We need to do this to be able
    00339    * to detect too long company name. */
    00340   char buffer[(MAX_LENGTH_COMPANY_NAME_CHARS + 1) * MAX_CHAR_LENGTH];
    00341
    00342   if (c->name_1 != STR_SV_UNNAMED) return;
    00343   if (c->last_build_coordinate == 0) return;
    00344
    00345   Town *t = ClosestTownFromTile(c->last_build_coordinate, UINT_MAX);
    00346
    00347   StringID str;
    00348   uint32 strp;
    00349   if (t->name == NULL && IsInsideMM(t->townnametype, SPECSTR_TOWNNAME_START, SPECSTR_TOWNNAME_LAST + 1)) {
    00350     str = t->townnametype - SPECSTR_TOWNNAME_START + SPECSTR_COMPANY_NAME_START;
    00351     strp = t->townnameparts;
    00352
    00353 verify_name:;
    00354     /* No companies must have this name already */
    00355     Company *cc;
    00356     FOR_ALL_COMPANIES(cc) {
    00357       if (cc->name_1 == str && cc->name_2 == strp) goto bad_town_name;
    00358     }
    00359
    00360     GetString(buffer, str, lastof(buffer));
    00361     if (Utf8StringLength(buffer) >= MAX_LENGTH_COMPANY_NAME_CHARS) goto bad_town_name;
    00362
    00363 set_name:;
    00364     c->name_1 = str;
    00365     c->name_2 = strp;
    00366
    00367     MarkWholeScreenDirty();
    00368
    00369     if (c->is_ai) {
    00370       CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
    00371       cni->FillData(c);
    00372       SetDParam(0, STR_NEWS_COMPANY_LAUNCH_TITLE);
    00373       SetDParam(1, STR_NEWS_COMPANY_LAUNCH_DESCRIPTION);
    00374       SetDParamStr(2, cni->company_name);
    00375       SetDParam(3, t->index);
    00376       AddNewsItem(STR_MESSAGE_NEWS_FORMAT, NS_COMPANY_NEW, NR_TILE, c->last_build_coordinate, NR_NONE, UINT32_MAX, cni);
    00377     }
    00378     return;
    00379   }
    00380 bad_town_name:;
    00381
    00382   if (c->president_name_1 == SPECSTR_PRESIDENT_NAME) {
    00383     str = SPECSTR_ANDCO_NAME;
    00384     strp = c->president_name_2;
    00385     goto set_name;
    00386   } else {
    00387     str = SPECSTR_ANDCO_NAME;
    00388     strp = Random();
    00389     goto verify_name;
    00390   }
    00391 }
    00392
    00394 static const byte _colour_sort[COLOUR_END] = {2, 2, 3, 2, 3, 2, 3, 2, 3, 2, 2, 2, 3, 1, 1, 1};
    00396 static const Colours _similar_colour[COLOUR_END][2] = {
    00397   { COLOUR_BLUE,       COLOUR_LIGHT_BLUE }, // COLOUR_DARK_BLUE
    00398   { COLOUR_GREEN,      COLOUR_DARK_GREEN }, // COLOUR_PALE_GREEN
    00399   { INVALID_COLOUR,    INVALID_COLOUR    }, // COLOUR_PINK
    00400   { COLOUR_ORANGE,     INVALID_COLOUR    }, // COLOUR_YELLOW
    00401   { INVALID_COLOUR,    INVALID_COLOUR    }, // COLOUR_RED
    00402   { COLOUR_DARK_BLUE,  COLOUR_BLUE       }, // COLOUR_LIGHT_BLUE
    00403   { COLOUR_PALE_GREEN, COLOUR_DARK_GREEN }, // COLOUR_GREEN
    00404   { COLOUR_PALE_GREEN, COLOUR_GREEN      }, // COLOUR_DARK_GREEN
    00405   { COLOUR_DARK_BLUE,  COLOUR_LIGHT_BLUE }, // COLOUR_BLUE
    00406   { COLOUR_BROWN,      COLOUR_ORANGE     }, // COLOUR_CREAM
    00407   { COLOUR_PURPLE,     INVALID_COLOUR    }, // COLOUR_MAUVE
    00408   { COLOUR_MAUVE,      INVALID_COLOUR    }, // COLOUR_PURPLE
    00409   { COLOUR_YELLOW,     COLOUR_CREAM      }, // COLOUR_ORANGE
    00410   { COLOUR_CREAM,      INVALID_COLOUR    }, // COLOUR_BROWN
    00411   { COLOUR_WHITE,      INVALID_COLOUR    }, // COLOUR_GREY
    00412   { COLOUR_GREY,       INVALID_COLOUR    }, // COLOUR_WHITE
    00413 };
    00414
    00419 static Colours GenerateCompanyColour()
    00420 {
    00421   Colours colours[COLOUR_END];
    00422
    00423   /* Initialize array */
    00424   for (uint i = 0; i < COLOUR_END; i++) colours[i] = (Colours)i;
    00425
    00426   /* And randomize it */
    00427   for (uint i = 0; i < 100; i++) {
    00428     uint r = Random();
    00429     Swap(colours[GB(r, 0, 4)], colours[GB(r, 4, 4)]);
    00430   }
    00431
    00432   /* Bubble sort it according to the values in table 1 */
    00433   for (uint i = 0; i < COLOUR_END; i++) {
    00434     for (uint j = 1; j < COLOUR_END; j++) {
    00435       if (_colour_sort[colours[j - 1]] < _colour_sort[colours[j]]) {
    00436         Swap(colours[j - 1], colours[j]);
    00437       }
    00438     }
    00439   }
    00440
    00441   /* Move the colours that look similar to each company's colour to the side */
    00442   Company *c;
    00443   FOR_ALL_COMPANIES(c) {
    00444     Colours pcolour = (Colours)c->colour;
    00445
    00446     for (uint i = 0; i < COLOUR_END; i++) {
    00447       if (colours[i] == pcolour) {
    00448         colours[i] = INVALID_COLOUR;
    00449         break;
    00450       }
    00451     }
    00452
    00453     for (uint j = 0; j < 2; j++) {
    00454       Colours similar = _similar_colour[pcolour][j];
    00455       if (similar == INVALID_COLOUR) break;
    00456
    00457       for (uint i = 1; i < COLOUR_END; i++) {
    00458         if (colours[i - 1] == similar) Swap(colours[i - 1], colours[i]);
    00459       }
    00460     }
    00461   }
    00462
    00463   /* Return the first available colour */
    00464   for (uint i = 0; i < COLOUR_END; i++) {
    00465     if (colours[i] != INVALID_COLOUR) return colours[i];
    00466   }
    00467
    00468   NOT_REACHED();
    00469 }
    00470
    00475 static void GeneratePresidentName(Company *c)
    00476 {
    00477   for (;;) {
    00478 restart:;
    00479     c->president_name_2 = Random();
    00480     c->president_name_1 = SPECSTR_PRESIDENT_NAME;
    00481
    00482     /* Reserve space for extra unicode character. We need to do this to be able
    00483      * to detect too long president name. */
    00484     char buffer[(MAX_LENGTH_PRESIDENT_NAME_CHARS + 1) * MAX_CHAR_LENGTH];
    00485     SetDParam(0, c->index);
    00486     GetString(buffer, STR_PRESIDENT_NAME, lastof(buffer));
    00487     if (Utf8StringLength(buffer) >= MAX_LENGTH_PRESIDENT_NAME_CHARS) continue;
    00488
    00489     Company *cc;
    00490     FOR_ALL_COMPANIES(cc) {
    00491       if (c != cc) {
    00492         /* Reserve extra space so even overlength president names can be compared. */
    00493         char buffer2[(MAX_LENGTH_PRESIDENT_NAME_CHARS + 1) * MAX_CHAR_LENGTH];
    00494         SetDParam(0, cc->index);
    00495         GetString(buffer2, STR_PRESIDENT_NAME, lastof(buffer2));
    00496         if (strcmp(buffer2, buffer) == 0) goto restart;
    00497       }
    00498     }
    00499     return;
    00500   }
    00501 }
    00502
    00508 void ResetCompanyLivery(Company *c)
    00509 {
    00510   for (LiveryScheme scheme = LS_BEGIN; scheme < LS_END; scheme++) {
    00511     c->livery[scheme].in_use  = false;
    00512     c->livery[scheme].colour1 = c->colour;
    00513     c->livery[scheme].colour2 = c->colour;
    00514   }
    00515 }
    00516
    00524 Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY)
    00525 {
    00526   if (!Company::CanAllocateItem()) return NULL;
    00527
    00528   /* we have to generate colour before this company is valid */
    00529   Colours colour = GenerateCompanyColour();
    00530
    00531   Company *c;
    00532   if (company == INVALID_COMPANY) {
    00533     c = new Company(STR_SV_UNNAMED, is_ai);
    00534   } else {
    00535     if (Company::IsValidID(company)) return NULL;
    00536     c = new (company) Company(STR_SV_UNNAMED, is_ai);
    00537   }
    00538
    00539   c->colour = colour;
    00540
    00541   ResetCompanyLivery(c);
    00542   _company_colours[c->index] = (Colours)c->colour;
    00543
    00544   c->money = c->current_loan = (100000ll * _economy.inflation_prices >> 16) / 50000 * 50000;
    00545
    00546   c->share_owners[0] = c->share_owners[1] = c->share_owners[2] = c->share_owners[3] = INVALID_OWNER;
    00547
    00548   c->avail_railtypes = GetCompanyRailtypes(c->index);
    00549   c->avail_roadtypes = GetCompanyRoadtypes(c->index);
    00550   c->inaugurated_year = _cur_year;
    00551   RandomCompanyManagerFaceBits(c->face, (GenderEthnicity)Random(), false); // create a random company manager face
    00552
    00553   SetDefaultCompanySettings(c->index);
    00554
    00555   GeneratePresidentName(c);
    00556
    00557   SetWindowDirty(WC_GRAPH_LEGEND, 0);
    00558   SetWindowClassesDirty(WC_CLIENT_LIST_POPUP);
    00559   SetWindowDirty(WC_CLIENT_LIST, 0);
    00560   BuildOwnerLegend();
    00561   InvalidateWindowData(WC_SMALLMAP, 0, 1);
    00562
    00563   if (is_ai && (!_networking || _network_server)) AI::StartNew(c->index);
    00564
    00565   AI::BroadcastNewEvent(new ScriptEventCompanyNew(c->index), c->index);
    00566   Game::NewEvent(new ScriptEventCompanyNew(c->index));
    00567
    00568   return c;
    00569 }
    00570
    00572 void StartupCompanies()
    00573 {
    00574   _next_competitor_start = 0;
    00575 }
    00576
    00578 static void MaybeStartNewCompany()
    00579 {
    00580 #ifdef ENABLE_NETWORK
    00581   if (_networking && Company::GetNumItems() >= _settings_client.network.max_companies) return;
    00582 #endif /* ENABLE_NETWORK */
    00583
    00584   Company *c;
    00585
    00586   /* count number of competitors */
    00587   uint n = 0;
    00588   FOR_ALL_COMPANIES(c) {
    00589     if (c->is_ai) n++;
    00590   }
    00591
    00592   if (n < (uint)_settings_game.difficulty.max_no_competitors) {
    00593     /* Send a command to all clients to start up a new AI.
    00594      * Works fine for Multiplayer and Singleplayer */
    00595     DoCommandP(0, 1 | INVALID_COMPANY << 16, 0, CMD_COMPANY_CTRL);
    00596   }
    00597 }
    00598
    00600 void InitializeCompanies()
    00601 {
    00602   _cur_company_tick_index = 0;
    00603 }
    00604
    00611 bool MayCompanyTakeOver(CompanyID cbig, CompanyID csmall)
    00612 {
    00613   const Company *c1 = Company::Get(cbig);
    00614   const Company *c2 = Company::Get(csmall);
    00615
    00616   /* Do the combined vehicle counts stay within the limits? */
    00617   return c1->group_all[VEH_TRAIN].num_vehicle + c2->group_all[VEH_TRAIN].num_vehicle <= _settings_game.vehicle.max_trains &&
    00618     c1->group_all[VEH_ROAD].num_vehicle     + c2->group_all[VEH_ROAD].num_vehicle     <= _settings_game.vehicle.max_roadveh &&
    00619     c1->group_all[VEH_SHIP].num_vehicle     + c2->group_all[VEH_SHIP].num_vehicle     <= _settings_game.vehicle.max_ships &&
    00620     c1->group_all[VEH_AIRCRAFT].num_vehicle + c2->group_all[VEH_AIRCRAFT].num_vehicle <= _settings_game.vehicle.max_aircraft;
    00621 }
    00622
    00632 static void HandleBankruptcyTakeover(Company *c)
    00633 {
    00634   /* Amount of time out for each company to take over a company;
    00635    * Timeout is a quarter (3 months of 30 days) divided over the
    00636    * number of companies. The minimum number of days in a quarter
    00637    * is 90: 31 in January, 28 in February and 31 in March.
    00638    * Note that the company going bankrupt can't buy itself. */
    00639   static const int TAKE_OVER_TIMEOUT = 3 * 30 * DAY_TICKS / (MAX_COMPANIES - 1);
    00640
    00641   assert(c->bankrupt_asked != 0);
    00642
    00643   /* We're currently asking some company to buy 'us' */
    00644   if (c->bankrupt_timeout != 0) {
    00645     c->bankrupt_timeout -= MAX_COMPANIES;
    00646     if (c->bankrupt_timeout > 0) return;
    00647     c->bankrupt_timeout = 0;
    00648
    00649     return;
    00650   }
    00651
    00652   /* Did we ask everyone for bankruptcy? If so, bail out. */
    00653   if (c->bankrupt_asked == MAX_UVALUE(CompanyMask)) return;
    00654
    00655   Company *c2, *best = NULL;
    00656   int32 best_performance = -1;
    00657
    00658   /* Ask the company with the highest performance history first */
    00659   FOR_ALL_COMPANIES(c2) {
    00660     if (c2->bankrupt_asked == 0 && // Don't ask companies going bankrupt themselves
    00661         !HasBit(c->bankrupt_asked, c2->index) &&
    00662         best_performance < c2->old_economy[1].performance_history &&
    00663         MayCompanyTakeOver(c2->index, c->index)) {
    00664       best_performance = c2->old_economy[1].performance_history;
    00665       best = c2;
    00666     }
    00667   }
    00668
    00669   /* Asked all companies? */
    00670   if (best_performance == -1) {
    00671     c->bankrupt_asked = MAX_UVALUE(CompanyMask);
    00672     return;
    00673   }
    00674
    00675   SetBit(c->bankrupt_asked, best->index);
    00676
    00677   c->bankrupt_timeout = TAKE_OVER_TIMEOUT;
    00678   if (best->is_ai) {
    00679     AI::NewEvent(best->index, new ScriptEventCompanyAskMerger(c->index, ClampToI32(c->bankrupt_value)));
    00680   } else if (IsInteractiveCompany(best->index)) {
    00681     ShowBuyCompanyDialog(c->index);
    00682   }
    00683 }
    00684
    00686 void OnTick_Companies()
    00687 {
    00688   if (_game_mode == GM_EDITOR) return;
    00689
    00690   Company *c = Company::GetIfValid(_cur_company_tick_index);
    00691   if (c != NULL) {
    00692     if (c->name_1 != 0) GenerateCompanyName(c);
    00693     if (c->bankrupt_asked != 0) HandleBankruptcyTakeover(c);
    00694   }
    00695
    00696   if (_next_competitor_start == 0) {
    00697     _next_competitor_start = AI::GetStartNextTime() * DAY_TICKS;
    00698   }
    00699
    00700   if (AI::CanStartNew() && _game_mode != GM_MENU && --_next_competitor_start == 0) {
    00701     MaybeStartNewCompany();
    00702   }
    00703
    00704   _cur_company_tick_index = (_cur_company_tick_index + 1) % MAX_COMPANIES;
    00705 }
    00706
    00711 void CompaniesYearlyLoop()
    00712 {
    00713   Company *c;
    00714
    00715   /* Copy statistics */
    00716   FOR_ALL_COMPANIES(c) {
    00717     memmove(&c->yearly_expenses[1], &c->yearly_expenses[0], sizeof(c->yearly_expenses) - sizeof(c->yearly_expenses[0]));
    00718     memset(&c->yearly_expenses[0], 0, sizeof(c->yearly_expenses[0]));
    00719     SetWindowDirty(WC_FINANCES, c->index);
    00720   }
    00721
    00722   if (_settings_client.gui.show_finances && _local_company != COMPANY_SPECTATOR) {
    00723     ShowCompanyFinances(_local_company);
    00724     c = Company::Get(_local_company);
    00725     if (c->num_valid_stat_ent > 5 && c->old_economy[0].performance_history < c->old_economy[4].performance_history) {
    00726       SndPlayFx(SND_01_BAD_YEAR);
    00727     } else {
    00728       SndPlayFx(SND_00_GOOD_YEAR);
    00729     }
    00730   }
    00731 }
    00732
    00738 void CompanyNewsInformation::FillData(const Company *c, const Company *other)
    00739 {
    00740   SetDParam(0, c->index);
    00741   GetString(this->company_name, STR_COMPANY_NAME, lastof(this->company_name));
    00742
    00743   if (other == NULL) {
    00744     *this->other_company_name = '\0';
    00745   } else {
    00746     SetDParam(0, other->index);
    00747     GetString(this->other_company_name, STR_COMPANY_NAME, lastof(this->other_company_name));
    00748     c = other;
    00749   }
    00750
    00751   SetDParam(0, c->index);
    00752   GetString(this->president_name, STR_PRESIDENT_NAME_MANAGER, lastof(this->president_name));
    00753
    00754   this->colour = c->colour;
    00755   this->face = c->face;
    00756
    00757 }
    00758
    00763 void CompanyAdminUpdate(const Company *company)
    00764 {
    00765 #ifdef ENABLE_NETWORK
    00766   if (_network_server) NetworkAdminCompanyUpdate(company);
    00767 #endif /* ENABLE_NETWORK */
    00768 }
    00769
    00775 void CompanyAdminRemove(CompanyID company_id, CompanyRemoveReason reason)
    00776 {
    00777 #ifdef ENABLE_NETWORK
    00778   if (_network_server) NetworkAdminCompanyRemove(company_id, (AdminCompanyRemoveReason)reason);
    00779 #endif /* ENABLE_NETWORK */
    00780 }
    00781
    00796 CommandCost CmdCompanyCtrl(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00797 {
    00798   InvalidateWindowData(WC_COMPANY_LEAGUE, 0, 0);
    00799   CompanyID company_id = (CompanyID)GB(p1, 16, 8);
    00800 #ifdef ENABLE_NETWORK
    00801   ClientID client_id = (ClientID)p2;
    00802 #endif /* ENABLE_NETWORK */
    00803
    00804   switch (GB(p1, 0, 16)) {
    00805     case 0: { // Create a new company
    00806       /* This command is only executed in a multiplayer game */
    00807       if (!_networking) return CMD_ERROR;
    00808
    00809 #ifdef ENABLE_NETWORK
    00810       /* Has the network client a correct ClientIndex? */
    00811       if (!(flags & DC_EXEC)) return CommandCost();
    00812       NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
    00813 #ifndef DEBUG_DUMP_COMMANDS
    00814       /* When replaying the client ID is not a valid client; there
    00815        * are actually no clients at all. However, the company has to
    00816        * be created, otherwise we cannot rerun the game properly.
    00817        * So only allow a NULL client info in that case. */
    00818       if (ci == NULL) return CommandCost();
    00819 #endif /* NOT DEBUG_DUMP_COMMANDS */
    00820
    00821       /* Delete multiplayer progress bar */
    00822       DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
    00823
    00824       Company *c = DoStartupNewCompany(false);
    00825
    00826       /* A new company could not be created, revert to being a spectator */
    00827       if (c == NULL) {
    00828         if (_network_server) {
    00829           ci->client_playas = COMPANY_SPECTATOR;
    00830           NetworkUpdateClientInfo(ci->client_id);
    00831         }
    00832         break;
    00833       }
    00834
    00835       /* This is the client (or non-dedicated server) who wants a new company */
    00836       if (client_id == _network_own_client_id) {
    00837         assert(_local_company == COMPANY_SPECTATOR);
    00838         SetLocalCompany(c->index);
    00839         if (!StrEmpty(_settings_client.network.default_company_pass)) {
    00840           NetworkChangeCompanyPassword(_local_company, _settings_client.network.default_company_pass);
    00841         }
    00842
    00843         /* Now that we have a new company, broadcast our company settings to
    00844          * all clients so everything is in sync */
    00845         SyncCompanySettings();
    00846
    00847         MarkWholeScreenDirty();
    00848       }
    00849
    00850       if (_network_server) {
    00851         if (ci != NULL) {
    00852           /* ci is only NULL when replaying.
    00853            * When replaying no client is actually in need of an update. */
    00854           ci->client_playas = c->index;
    00855           NetworkUpdateClientInfo(ci->client_id);
    00856         }
    00857
    00858         if (Company::IsValidID(c->index)) {
    00859           _network_company_states[c->index].months_empty = 0;
    00860           _network_company_states[c->index].password[0] = '\0';
    00861           NetworkServerUpdateCompanyPassworded(c->index, false);
    00862
    00863           /* XXX - When a client joins, we automatically set its name to the
    00864            * client's name (for some reason). As it stands now only the server
    00865            * knows the client's name, so it needs to send out a "broadcast" to
    00866            * do this. To achieve this we send a network command. However, it
    00867            * uses _local_company to execute the command as.  To prevent abuse
    00868            * (eg. only yourself can change your name/company), we 'cheat' by
    00869            * impersonation _local_company as the server. Not the best solution;
    00870            * but it works.
    00871            * TODO: Perhaps this could be improved by when the client is ready
    00872            * with joining to let it send itself the command, and not the server?
    00873            * For example in network_client.c:534? */
    00874           if (ci != NULL) {
    00875             /* ci is only NULL when replaying.
    00876              * When replaying, the command to rename the president will
    00877              * automatically be ran, so this is not even needed to get
    00878              * the exact same state. */
    00879             NetworkSendCommand(0, 0, 0, CMD_RENAME_PRESIDENT, NULL, ci->client_name, c->index);
    00880           }
    00881         }
    00882
    00883         /* Announce new company on network. */
    00884         NetworkAdminCompanyInfo(c, true);
    00885
    00886         if (ci != NULL) {
    00887           /* ci is only NULL when replaying.
    00888            * When replaying, the message that someone started a new company
    00889            * is not interesting at all. */
    00890           NetworkServerSendChat(NETWORK_ACTION_COMPANY_NEW, DESTTYPE_BROADCAST, 0, "", ci->client_id, c->index + 1);
    00891         }
    00892       }
    00893 #endif /* ENABLE_NETWORK */
    00894       break;
    00895     }
    00896
    00897     case 1: // Make a new AI company
    00898       if (!(flags & DC_EXEC)) return CommandCost();
    00899
    00900       if (company_id != INVALID_COMPANY && (company_id >= MAX_COMPANIES || Company::IsValidID(company_id))) return CMD_ERROR;
    00901       DoStartupNewCompany(true, company_id);
    00902       break;
    00903
    00904     case 2: { // Delete a company
    00905       CompanyRemoveReason reason = (CompanyRemoveReason)GB(p2, 0, 2);
    00906       if (reason >= CRR_END) return CMD_ERROR;
    00907
    00908       Company *c = Company::GetIfValid(company_id);
    00909       if (c == NULL) return CMD_ERROR;
    00910
    00911       if (!(flags & DC_EXEC)) return CommandCost();
    00912
    00913       /* Delete any open window of the company */
    00914       DeleteCompanyWindows(c->index);
    00915       CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
    00916       cni->FillData(c);
    00917
    00918       /* Show the bankrupt news */
    00919       SetDParam(0, STR_NEWS_COMPANY_BANKRUPT_TITLE);
    00920       SetDParam(1, STR_NEWS_COMPANY_BANKRUPT_DESCRIPTION);
    00921       SetDParamStr(2, cni->company_name);
    00922       AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, NS_COMPANY_BANKRUPT, cni);
    00923
    00924       /* Remove the company */
    00925       ChangeOwnershipOfCompanyItems(c->index, INVALID_OWNER);
    00926       if (c->is_ai) AI::Stop(c->index);
    00927
    00928       CompanyID c_index = c->index;
    00929       delete c;
    00930       AI::BroadcastNewEvent(new ScriptEventCompanyBankrupt(c_index));
    00931       Game::NewEvent(new ScriptEventCompanyBankrupt(c_index));
    00932       CompanyAdminRemove(c_index, (CompanyRemoveReason)reason);
    00933       break;
    00934     }
    00935
    00936     default: return CMD_ERROR;
    00937   }
    00938
    00939   InvalidateWindowClassesData(WC_GAME_OPTIONS);
    00940   InvalidateWindowClassesData(WC_AI_SETTINGS);
    00941   InvalidateWindowClassesData(WC_AI_LIST);
    00942
    00943   return CommandCost();
    00944 }
    00945
    00955 CommandCost CmdSetCompanyManagerFace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00956 {
    00957   CompanyManagerFace cmf = (CompanyManagerFace)p2;
    00958
    00959   if (!IsValidCompanyManagerFace(cmf)) return CMD_ERROR;
    00960
    00961   if (flags & DC_EXEC) {
    00962     Company::Get(_current_company)->face = cmf;
    00963     MarkWholeScreenDirty();
    00964   }
    00965   return CommandCost();
    00966 }
    00967
    00979 CommandCost CmdSetCompanyColour(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00980 {
    00981   Colours colour = Extract<Colours, 0, 4>(p2);
    00982   LiveryScheme scheme = Extract<LiveryScheme, 0, 8>(p1);
    00983   byte state = GB(p1, 8, 2);
    00984
    00985   if (scheme >= LS_END || state >= 3 || colour == INVALID_COLOUR) return CMD_ERROR;
    00986
    00987   Company *c = Company::Get(_current_company);
    00988
    00989   /* Ensure no two companies have the same primary colour */
    00990   if (scheme == LS_DEFAULT && state == 0) {
    00991     const Company *cc;
    00992     FOR_ALL_COMPANIES(cc) {
    00993       if (cc != c && cc->colour == colour) return CMD_ERROR;
    00994     }
    00995   }
    00996
    00997   if (flags & DC_EXEC) {
    00998     switch (state) {
    00999       case 0:
    01000         c->livery[scheme].colour1 = colour;
    01001
    01002         /* If setting the first colour of the default scheme, adjust the
    01003          * original and cached company colours too. */
    01004         if (scheme == LS_DEFAULT) {
    01005           _company_colours[_current_company] = colour;
    01006           c->colour = colour;
    01007           CompanyAdminUpdate(c);
    01008         }
    01009         break;
    01010
    01011       case 1:
    01012         c->livery[scheme].colour2 = colour;
    01013         break;
    01014
    01015       case 2:
    01016         c->livery[scheme].in_use = colour != 0;
    01017
    01018         /* Now handle setting the default scheme's in_use flag.
    01019          * This is different to the other schemes, as it signifies if any
    01020          * scheme is active at all. If this flag is not set, then no
    01021          * processing of vehicle types occurs at all, and only the default
    01022          * colours will be used. */
    01023
    01024         /* If enabling a scheme, set the default scheme to be in use too */
    01025         if (colour != 0) {
    01026           c->livery[LS_DEFAULT].in_use = true;
    01027           break;
    01028         }
    01029
    01030         /* Else loop through all schemes to see if any are left enabled.
    01031          * If not, disable the default scheme too. */
    01032         c->livery[LS_DEFAULT].in_use = false;
    01033         for (scheme = LS_DEFAULT; scheme < LS_END; scheme++) {
    01034           if (c->livery[scheme].in_use) {
    01035             c->livery[LS_DEFAULT].in_use = true;
    01036             break;
    01037           }
    01038         }
    01039         break;
    01040
    01041       default:
    01042         break;
    01043     }
    01044     ResetVehicleColourMap();
    01045     MarkWholeScreenDirty();
    01046
    01047     /* All graph related to companies use the company colour. */
    01048     InvalidateWindowData(WC_INCOME_GRAPH, 0);
    01049     InvalidateWindowData(WC_OPERATING_PROFIT, 0);
    01050     InvalidateWindowData(WC_DELIVERED_CARGO, 0);
    01051     InvalidateWindowData(WC_PERFORMANCE_HISTORY, 0);
    01052     InvalidateWindowData(WC_COMPANY_VALUE, 0);
    01053     /* The smallmap owner view also stores the company colours. */
    01054     BuildOwnerLegend();
    01055     InvalidateWindowData(WC_SMALLMAP, 0, 1);
    01056
    01057     /* Company colour data is indirectly cached. */
    01058     Vehicle *v;
    01059     FOR_ALL_VEHICLES(v) {
    01060       if (v->owner == _current_company) v->InvalidateNewGRFCache();
    01061     }
    01062
    01063     extern void UpdateObjectColours(const Company *c);
    01064     UpdateObjectColours(c);
    01065   }
    01066   return CommandCost();
    01067 }
    01068
    01074 static bool IsUniqueCompanyName(const char *name)
    01075 {
    01076   const Company *c;
    01077
    01078   FOR_ALL_COMPANIES(c) {
    01079     if (c->name != NULL && strcmp(c->name, name) == 0) return false;
    01080   }
    01081
    01082   return true;
    01083 }
    01084
    01094 CommandCost CmdRenameCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01095 {
    01096   bool reset = StrEmpty(text);
    01097
    01098   if (!reset) {
    01099     if (Utf8StringLength(text) >= MAX_LENGTH_COMPANY_NAME_CHARS) return CMD_ERROR;
    01100     if (!IsUniqueCompanyName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
    01101   }
    01102
    01103   if (flags & DC_EXEC) {
    01104     Company *c = Company::Get(_current_company);
    01105     free(c->name);
    01106     c->name = reset ? NULL : strdup(text);
    01107     MarkWholeScreenDirty();
    01108     CompanyAdminUpdate(c);
    01109   }
    01110
    01111   return CommandCost();
    01112 }
    01113
    01119 static bool IsUniquePresidentName(const char *name)
    01120 {
    01121   const Company *c;
    01122
    01123   FOR_ALL_COMPANIES(c) {
    01124     if (c->president_name != NULL && strcmp(c->president_name, name) == 0) return false;
    01125   }
    01126
    01127   return true;
    01128 }
    01129
    01139 CommandCost CmdRenamePresident(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01140 {
    01141   bool reset = StrEmpty(text);
    01142
    01143   if (!reset) {
    01144     if (Utf8StringLength(text) >= MAX_LENGTH_PRESIDENT_NAME_CHARS) return CMD_ERROR;
    01145     if (!IsUniquePresidentName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
    01146   }
    01147
    01148   if (flags & DC_EXEC) {
    01149     Company *c = Company::Get(_current_company);
    01150     free(c->president_name);
    01151
    01152     if (reset) {
    01153       c->president_name = NULL;
    01154     } else {
    01155       c->president_name = strdup(text);
    01156
    01157       if (c->name_1 == STR_SV_UNNAMED && c->name == NULL) {
    01158         char buf[80];
    01159
    01160         snprintf(buf, lengthof(buf), "%s Transport", text);
    01161         DoCommand(0, 0, 0, DC_EXEC, CMD_RENAME_COMPANY, buf);
    01162       }
    01163     }
    01164
    01165     MarkWholeScreenDirty();
    01166     CompanyAdminUpdate(c);
    01167   }
    01168
    01169   return CommandCost();
    01170 }