company_cmd.cpp

Go to the documentation of this file.
00001 /* $Id: company_cmd.cpp 18809 2010-01-15 16:41:15Z 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 static void MaybeStartNewCompany()
00511 {
00512 #ifdef ENABLE_NETWORK
00513   if (_networking && Company::GetNumItems() >= _settings_client.network.max_companies) return;
00514 #endif /* ENABLE_NETWORK */
00515 
00516   Company *c;
00517 
00518   /* count number of competitors */
00519   uint n = 0;
00520   FOR_ALL_COMPANIES(c) {
00521     if (c->is_ai) n++;
00522   }
00523 
00524   if (n < (uint)_settings_game.difficulty.max_no_competitors) {
00525     /* Send a command to all clients to start up a new AI.
00526      * Works fine for Multiplayer and Singleplayer */
00527     DoCommandP(0, 1, INVALID_COMPANY, CMD_COMPANY_CTRL);
00528   }
00529 }
00530 
00531 void InitializeCompanies()
00532 {
00533   _company_pool.CleanPool();
00534   _cur_company_tick_index = 0;
00535 }
00536 
00546 static void HandleBankruptcyTakeover(Company *c)
00547 {
00548   /* Amount of time out for each company to take over a company;
00549    * Timeout is a quarter (3 months of 30 days) divided over the
00550    * number of companies. The minimum number of days in a quarter
00551    * is 90: 31 in January, 28 in February and 31 in March.
00552    * Note that the company going bankrupt can't buy itself. */
00553   static const int TAKE_OVER_TIMEOUT = 3 * 30 * DAY_TICKS / (MAX_COMPANIES - 1);
00554 
00555   assert(c->bankrupt_asked != 0);
00556 
00557   /* We're currently asking some company to buy 'us' */
00558   if (c->bankrupt_timeout != 0) {
00559     c->bankrupt_timeout -= MAX_COMPANIES;
00560     if (c->bankrupt_timeout > 0) return;
00561     c->bankrupt_timeout = 0;
00562 
00563     return;
00564   }
00565 
00566   /* Did we ask everyone for bankruptcy? If so, bail out. */
00567   if (c->bankrupt_asked == MAX_UVALUE(CompanyMask)) return;
00568 
00569   Company *c2, *best = NULL;
00570   int32 best_performance = -1;
00571 
00572   /* Ask the company with the highest performance history first */
00573   FOR_ALL_COMPANIES(c2) {
00574     if (c2->bankrupt_asked == 0 && // Don't ask companies going bankrupt themselves
00575         !HasBit(c->bankrupt_asked, c2->index) &&
00576         best_performance < c2->old_economy[1].performance_history) {
00577       best_performance = c2->old_economy[1].performance_history;
00578       best = c2;
00579     }
00580   }
00581 
00582   /* Asked all companies? */
00583   if (best_performance == -1) {
00584     c->bankrupt_asked = MAX_UVALUE(CompanyMask);
00585     return;
00586   }
00587 
00588   SetBit(c->bankrupt_asked, best->index);
00589 
00590   if (IsInteractiveCompany(best->index)) {
00591     c->bankrupt_timeout = TAKE_OVER_TIMEOUT;
00592     ShowBuyCompanyDialog(c->index);
00593     return;
00594   }
00595 
00596   if (best->is_ai) {
00597     AI::NewEvent(best->index, new AIEventCompanyAskMerger(c->index, ClampToI32(c->bankrupt_value)));
00598   }
00599 }
00600 
00601 void OnTick_Companies()
00602 {
00603   if (_game_mode == GM_EDITOR) return;
00604 
00605   Company *c = Company::GetIfValid(_cur_company_tick_index);
00606   if (c != NULL) {
00607     if (c->name_1 != 0) GenerateCompanyName(c);
00608     if (c->bankrupt_asked != 0) HandleBankruptcyTakeover(c);
00609   }
00610 
00611   if (_next_competitor_start == 0) {
00612     _next_competitor_start = AI::GetStartNextTime() * DAY_TICKS;
00613   }
00614 
00615   if (AI::CanStartNew() && _game_mode != GM_MENU && --_next_competitor_start == 0) {
00616     MaybeStartNewCompany();
00617   }
00618 
00619   _cur_company_tick_index = (_cur_company_tick_index + 1) % MAX_COMPANIES;
00620 }
00621 
00622 void CompaniesYearlyLoop()
00623 {
00624   Company *c;
00625 
00626   /* Copy statistics */
00627   FOR_ALL_COMPANIES(c) {
00628     memmove(&c->yearly_expenses[1], &c->yearly_expenses[0], sizeof(c->yearly_expenses) - sizeof(c->yearly_expenses[0]));
00629     memset(&c->yearly_expenses[0], 0, sizeof(c->yearly_expenses[0]));
00630     SetWindowDirty(WC_FINANCES, c->index);
00631   }
00632 
00633   if (_settings_client.gui.show_finances && _local_company != COMPANY_SPECTATOR) {
00634     ShowCompanyFinances(_local_company);
00635     c = Company::Get(_local_company);
00636     if (c->num_valid_stat_ent > 5 && c->old_economy[0].performance_history < c->old_economy[4].performance_history) {
00637       SndPlayFx(SND_01_BAD_YEAR);
00638     } else {
00639       SndPlayFx(SND_00_GOOD_YEAR);
00640     }
00641   }
00642 }
00643 
00655 CommandCost CmdSetAutoReplace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00656 {
00657   Company *c = Company::GetIfValid(_current_company);
00658   if (c == NULL) return CMD_ERROR;
00659 
00660   EngineID old_engine_type = GB(p2, 0, 16);
00661   EngineID new_engine_type = GB(p2, 16, 16);
00662   GroupID id_g = GB(p1, 16, 16);
00663   CommandCost cost;
00664 
00665   if (!Group::IsValidID(id_g) && !IsAllGroupID(id_g) && !IsDefaultGroupID(id_g)) return CMD_ERROR;
00666   if (new_engine_type != INVALID_ENGINE) {
00667     if (!CheckAutoreplaceValidity(old_engine_type, new_engine_type, _current_company)) return CMD_ERROR;
00668 
00669     cost = AddEngineReplacementForCompany(c, old_engine_type, new_engine_type, id_g, flags);
00670   } else {
00671     cost = RemoveEngineReplacementForCompany(c, old_engine_type, id_g, flags);
00672   }
00673 
00674   if (IsLocalCompany()) InvalidateAutoreplaceWindow(old_engine_type, id_g);
00675 
00676   return cost;
00677 }
00678 
00684 void CompanyNewsInformation::FillData(const Company *c, const Company *other)
00685 {
00686   SetDParam(0, c->index);
00687   GetString(this->company_name, STR_COMPANY_NAME, lastof(this->company_name));
00688 
00689   if (other == NULL) {
00690     *this->other_company_name = '\0';
00691   } else {
00692     SetDParam(0, other->index);
00693     GetString(this->other_company_name, STR_COMPANY_NAME, lastof(this->other_company_name));
00694     c = other;
00695   }
00696 
00697   SetDParam(0, c->index);
00698   GetString(this->president_name, STR_PRESIDENT_NAME_MANAGER, lastof(this->president_name));
00699 
00700   this->colour = c->colour;
00701   this->face = c->face;
00702 
00703 }
00704 
00726 CommandCost CmdCompanyCtrl(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00727 {
00728   if (flags & DC_EXEC) _current_company = OWNER_NONE;
00729 
00730   InvalidateWindowData(WC_COMPANY_LEAGUE, 0, 0);
00731 
00732   switch (p1) {
00733     case 0: { // Create a new company
00734       /* This command is only executed in a multiplayer game */
00735       if (!_networking) return CMD_ERROR;
00736 
00737 #ifdef ENABLE_NETWORK
00738 
00739       /* Joining Client:
00740        * _local_company: COMPANY_SPECTATOR
00741        * cid = clientid
00742        *
00743        * Other client(s)/server:
00744        * _local_company: what they play as
00745        * cid = requested company/company of joining client */
00746       ClientID cid = (ClientID)p2;
00747 
00748       /* Has the network client a correct ClientIndex? */
00749       if (!(flags & DC_EXEC)) return CommandCost();
00750       NetworkClientInfo *ci = NetworkFindClientInfoFromClientID(cid);
00751       if (ci == NULL) return CommandCost();
00752 
00753       /* Delete multiplayer progress bar */
00754       DeleteWindowById(WC_NETWORK_STATUS_WINDOW, 0);
00755 
00756       Company *c = DoStartupNewCompany(false);
00757 
00758       /* A new company could not be created, revert to being a spectator */
00759       if (c == NULL) {
00760         if (_network_server) {
00761           ci->client_playas = COMPANY_SPECTATOR;
00762           NetworkUpdateClientInfo(ci->client_id);
00763         }
00764         break;
00765       }
00766 
00767       /* This is the client (or non-dedicated server) who wants a new company */
00768       if (cid == _network_own_client_id) {
00769         assert(_local_company == COMPANY_SPECTATOR);
00770         SetLocalCompany(c->index);
00771         if (!StrEmpty(_settings_client.network.default_company_pass)) {
00772           char *password = _settings_client.network.default_company_pass;
00773           NetworkChangeCompanyPassword(1, &password);
00774         }
00775 
00776         _current_company = _local_company;
00777 
00778         /* Now that we have a new company, broadcast our company settings to
00779          * all clients so everything is in sync */
00780         SyncCompanySettings();
00781 
00782         MarkWholeScreenDirty();
00783       }
00784 
00785       if (_network_server) {
00786         /* XXX - UGLY! p2 (pid) is mis-used to fetch the client-id, done at
00787          * server side in network_server.c:838, function
00788          * DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_COMMAND) */
00789         CompanyID old_playas = ci->client_playas;
00790         ci->client_playas = c->index;
00791         NetworkUpdateClientInfo(ci->client_id);
00792 
00793         if (Company::IsValidID(ci->client_playas)) {
00794           _network_company_states[c->index].months_empty = 0;
00795           _network_company_states[c->index].password[0] = '\0';
00796           NetworkServerUpdateCompanyPassworded(ci->client_playas, false);
00797 
00798           /* XXX - When a client joins, we automatically set its name to the
00799            * client's name (for some reason). As it stands now only the server
00800            * knows the client's name, so it needs to send out a "broadcast" to
00801            * do this. To achieve this we send a network command. However, it
00802            * uses _local_company to execute the command as.  To prevent abuse
00803            * (eg. only yourself can change your name/company), we 'cheat' by
00804            * impersonation _local_company as the server. Not the best solution;
00805            * but it works.
00806            * TODO: Perhaps this could be improved by when the client is ready
00807            * with joining to let it send itself the command, and not the server?
00808            * For example in network_client.c:534? */
00809           NetworkSend_Command(0, 0, 0, CMD_RENAME_PRESIDENT, NULL, ci->client_name, ci->client_playas);
00810         }
00811 
00812         /* Announce new company on network, if the client was a SPECTATOR before */
00813         if (old_playas == COMPANY_SPECTATOR) {
00814           NetworkServerSendChat(NETWORK_ACTION_COMPANY_NEW, DESTTYPE_BROADCAST, 0, "", ci->client_id, ci->client_playas + 1);
00815         }
00816       }
00817 #endif /* ENABLE_NETWORK */
00818     } break;
00819 
00820     case 1: // Make a new AI company
00821       if (!(flags & DC_EXEC)) return CommandCost();
00822 
00823       if (p2 != INVALID_COMPANY && (p2 >= MAX_COMPANIES || Company::IsValidID(p2))) return CMD_ERROR;
00824       DoStartupNewCompany(true, (CompanyID)p2);
00825       break;
00826 
00827     case 2: { // Delete a company
00828       Company *c = Company::GetIfValid(p2);
00829       if (c == NULL) return CMD_ERROR;
00830 
00831       if (!(flags & DC_EXEC)) return CommandCost();
00832 
00833       /* Delete any open window of the company */
00834       DeleteCompanyWindows(c->index);
00835       CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
00836       cni->FillData(c);
00837 
00838       /* Show the bankrupt news */
00839       SetDParam(0, STR_NEWS_COMPANY_BANKRUPT_TITLE);
00840       SetDParam(1, STR_NEWS_COMPANY_BANKRUPT_DESCRIPTION);
00841       SetDParamStr(2, cni->company_name);
00842       AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, NS_COMPANY_BANKRUPT, cni);
00843 
00844       /* Remove the company */
00845       ChangeOwnershipOfCompanyItems(c->index, INVALID_OWNER);
00846       if (c->is_ai) AI::Stop(c->index);
00847 
00848       CompanyID c_index = c->index;
00849       delete c;
00850       AI::BroadcastNewEvent(new AIEventCompanyBankrupt(c_index));
00851     } break;
00852 
00853     default: return CMD_ERROR;
00854   }
00855 
00856   return CommandCost();
00857 }
00858 
00867 CommandCost CmdSetCompanyManagerFace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00868 {
00869   CompanyManagerFace cmf = (CompanyManagerFace)p2;
00870 
00871   if (!IsValidCompanyManagerFace(cmf)) return CMD_ERROR;
00872 
00873   if (flags & DC_EXEC) {
00874     Company::Get(_current_company)->face = cmf;
00875     MarkWholeScreenDirty();
00876   }
00877   return CommandCost();
00878 }
00879 
00890 CommandCost CmdSetCompanyColour(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00891 {
00892   if (p2 >= 16) return CMD_ERROR; // max 16 colours
00893 
00894   Colours colour = (Colours)p2;
00895 
00896   LiveryScheme scheme = (LiveryScheme)GB(p1, 0, 8);
00897   byte state = GB(p1, 8, 2);
00898 
00899   if (scheme >= LS_END || state >= 3) return CMD_ERROR;
00900 
00901   Company *c = Company::Get(_current_company);
00902 
00903   /* Ensure no two companies have the same primary colour */
00904   if (scheme == LS_DEFAULT && state == 0) {
00905     const Company *cc;
00906     FOR_ALL_COMPANIES(cc) {
00907       if (cc != c && cc->colour == colour) return CMD_ERROR;
00908     }
00909   }
00910 
00911   if (flags & DC_EXEC) {
00912     switch (state) {
00913       case 0:
00914         c->livery[scheme].colour1 = colour;
00915 
00916         /* If setting the first colour of the default scheme, adjust the
00917          * original and cached company colours too. */
00918         if (scheme == LS_DEFAULT) {
00919           _company_colours[_current_company] = colour;
00920           c->colour = colour;
00921         }
00922         break;
00923 
00924       case 1:
00925         c->livery[scheme].colour2 = colour;
00926         break;
00927 
00928       case 2:
00929         c->livery[scheme].in_use = colour != 0;
00930 
00931         /* Now handle setting the default scheme's in_use flag.
00932          * This is different to the other schemes, as it signifies if any
00933          * scheme is active at all. If this flag is not set, then no
00934          * processing of vehicle types occurs at all, and only the default
00935          * colours will be used. */
00936 
00937         /* If enabling a scheme, set the default scheme to be in use too */
00938         if (colour != 0) {
00939           c->livery[LS_DEFAULT].in_use = true;
00940           break;
00941         }
00942 
00943         /* Else loop through all schemes to see if any are left enabled.
00944          * If not, disable the default scheme too. */
00945         c->livery[LS_DEFAULT].in_use = false;
00946         for (scheme = LS_DEFAULT; scheme < LS_END; scheme++) {
00947           if (c->livery[scheme].in_use) {
00948             c->livery[LS_DEFAULT].in_use = true;
00949             break;
00950           }
00951         }
00952         break;
00953 
00954       default:
00955         break;
00956     }
00957     ResetVehicleColourMap();
00958     MarkWholeScreenDirty();
00959 
00960     /* Company colour data is indirectly cached. */
00961     Vehicle *v;
00962     FOR_ALL_VEHICLES(v) {
00963       if (v->owner == _current_company) v->InvalidateNewGRFCache();
00964     }
00965   }
00966   return CommandCost();
00967 }
00968 
00969 static bool IsUniqueCompanyName(const char *name)
00970 {
00971   const Company *c;
00972 
00973   FOR_ALL_COMPANIES(c) {
00974     if (c->name != NULL && strcmp(c->name, name) == 0) return false;
00975   }
00976 
00977   return true;
00978 }
00979 
00988 CommandCost CmdRenameCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00989 {
00990   bool reset = StrEmpty(text);
00991 
00992   if (!reset) {
00993     if (strlen(text) >= MAX_LENGTH_COMPANY_NAME_BYTES) return CMD_ERROR;
00994     if (!IsUniqueCompanyName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
00995   }
00996 
00997   if (flags & DC_EXEC) {
00998     Company *c = Company::Get(_current_company);
00999     free(c->name);
01000     c->name = reset ? NULL : strdup(text);
01001     MarkWholeScreenDirty();
01002   }
01003 
01004   return CommandCost();
01005 }
01006 
01007 static bool IsUniquePresidentName(const char *name)
01008 {
01009   const Company *c;
01010 
01011   FOR_ALL_COMPANIES(c) {
01012     if (c->president_name != NULL && strcmp(c->president_name, name) == 0) return false;
01013   }
01014 
01015   return true;
01016 }
01017 
01026 CommandCost CmdRenamePresident(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01027 {
01028   bool reset = StrEmpty(text);
01029 
01030   if (!reset) {
01031     if (strlen(text) >= MAX_LENGTH_PRESIDENT_NAME_BYTES) return CMD_ERROR;
01032     if (!IsUniquePresidentName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
01033   }
01034 
01035   if (flags & DC_EXEC) {
01036     Company *c = Company::Get(_current_company);
01037     free(c->president_name);
01038 
01039     if (reset) {
01040       c->president_name = NULL;
01041     } else {
01042       c->president_name = strdup(text);
01043 
01044       if (c->name_1 == STR_SV_UNNAMED && c->name == NULL) {
01045         char buf[80];
01046 
01047         snprintf(buf, lengthof(buf), "%s Transport", text);
01048         DoCommand(0, 0, 0, DC_EXEC, CMD_RENAME_COMPANY, buf);
01049       }
01050     }
01051 
01052     MarkWholeScreenDirty();
01053   }
01054 
01055   return CommandCost();
01056 }

Generated on Wed Jan 20 23:38:34 2010 for OpenTTD by  doxygen 1.5.6