company_cmd.cpp

Go to the documentation of this file.
00001 /* $Id: company_cmd.cpp 21637 2010-12-25 19:47: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_base.h"
00015 #include "company_func.h"
00016 #include "company_gui.h"
00017 #include "town.h"
00018 #include "news_func.h"
00019 #include "cmd_helper.h"
00020 #include "command_func.h"
00021 #include "network/network.h"
00022 #include "network/network_func.h"
00023 #include "network/network_base.h"
00024 #include "network/network_admin.h"
00025 #include "ai/ai.hpp"
00026 #include "company_manager_face.h"
00027 #include "window_func.h"
00028 #include "strings_func.h"
00029 #include "date_func.h"
00030 #include "sound_func.h"
00031 #include "rail.h"
00032 #include "core/pool_func.hpp"
00033 #include "settings_func.h"
00034 #include "vehicle_base.h"
00035 #include "vehicle_func.h"
00036 #include "sprite.h"
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   for (uint j = 0; j < 4; j++) this->share_owners[j] = COMPANY_SPECTATOR;
00061   InvalidateWindowData(WC_PERFORMANCE_DETAIL, 0, INVALID_COMPANY);
00062 }
00063 
00065 Company::~Company()
00066 {
00067   free(this->num_engines);
00068 
00069   if (CleaningPool()) return;
00070 
00071   DeleteCompanyWindows(this->index);
00072 }
00073 
00078 void Company::PostDestructor(size_t index)
00079 {
00080   InvalidateWindowData(WC_GRAPH_LEGEND, 0, (int)index);
00081   InvalidateWindowData(WC_PERFORMANCE_DETAIL, 0, (int)index);
00082   InvalidateWindowData(WC_COMPANY_LEAGUE, 0, 0);
00083   /* If the currently shown error message has this company in it, then close it. */
00084   InvalidateWindowData(WC_ERRMSG, 0);
00085 }
00086 
00093 void SetLocalCompany(CompanyID new_company)
00094 {
00095   /* company could also be COMPANY_SPECTATOR or OWNER_NONE */
00096   assert(Company::IsValidID(new_company) || new_company == COMPANY_SPECTATOR || new_company == OWNER_NONE);
00097 
00098 #ifdef ENABLE_NETWORK
00099   /* Delete the chat window, if you were team chatting. */
00100   InvalidateWindowData(WC_SEND_NETWORK_MSG, DESTTYPE_TEAM, _local_company);
00101 #endif
00102 
00103   assert(IsLocalCompany());
00104 
00105   _current_company = _local_company = new_company;
00106 
00107   /* Delete any construction windows... */
00108   DeleteConstructionWindows();
00109 
00110   /* ... and redraw the whole screen. */
00111   MarkWholeScreenDirty();
00112 }
00113 
00119 uint16 GetDrawStringCompanyColour(CompanyID company)
00120 {
00121   if (!Company::IsValidID(company)) return _colour_gradient[COLOUR_WHITE][4] | TC_IS_PALETTE_COLOUR;
00122   return (_colour_gradient[_company_colours[company]][4]) | TC_IS_PALETTE_COLOUR;
00123 }
00124 
00131 void DrawCompanyIcon(CompanyID c, int x, int y)
00132 {
00133   DrawSprite(SPR_COMPANY_ICON, COMPANY_SPRITE_COLOUR(c), x, y);
00134 }
00135 
00142 static bool IsValidCompanyManagerFace(CompanyManagerFace cmf)
00143 {
00144   if (!AreCompanyManagerFaceBitsValid(cmf, CMFV_GEN_ETHN, GE_WM)) return false;
00145 
00146   GenderEthnicity ge   = (GenderEthnicity)GetCompanyManagerFaceBits(cmf, CMFV_GEN_ETHN, GE_WM);
00147   bool has_moustache   = !HasBit(ge, GENDER_FEMALE) && GetCompanyManagerFaceBits(cmf, CMFV_HAS_MOUSTACHE,   ge) != 0;
00148   bool has_tie_earring = !HasBit(ge, GENDER_FEMALE) || GetCompanyManagerFaceBits(cmf, CMFV_HAS_TIE_EARRING, ge) != 0;
00149   bool has_glasses     = GetCompanyManagerFaceBits(cmf, CMFV_HAS_GLASSES, ge) != 0;
00150 
00151   if (!AreCompanyManagerFaceBitsValid(cmf, CMFV_EYE_COLOUR, ge)) return false;
00152   for (CompanyManagerFaceVariable cmfv = CMFV_CHEEKS; cmfv < CMFV_END; cmfv++) {
00153     switch (cmfv) {
00154       case CMFV_MOUSTACHE:   if (!has_moustache)   continue; break;
00155       case CMFV_LIPS:        // FALL THROUGH
00156       case CMFV_NOSE:        if (has_moustache)    continue; break;
00157       case CMFV_TIE_EARRING: if (!has_tie_earring) continue; break;
00158       case CMFV_GLASSES:     if (!has_glasses)     continue; break;
00159       default: break;
00160     }
00161     if (!AreCompanyManagerFaceBitsValid(cmf, cmfv, ge)) return false;
00162   }
00163 
00164   return true;
00165 }
00166 
00171 void InvalidateCompanyWindows(const Company *company)
00172 {
00173   CompanyID cid = company->index;
00174 
00175   if (cid == _local_company) SetWindowDirty(WC_STATUS_BAR, 0);
00176   SetWindowDirty(WC_FINANCES, cid);
00177 }
00178 
00184 bool CheckCompanyHasMoney(CommandCost &cost)
00185 {
00186   if (cost.GetCost() > 0) {
00187     const Company *c = Company::GetIfValid(_current_company);
00188     if (c != NULL && cost.GetCost() > c->money) {
00189       SetDParam(0, cost.GetCost());
00190       cost.MakeError(STR_ERROR_NOT_ENOUGH_CASH_REQUIRES_CURRENCY);
00191       return false;
00192     }
00193   }
00194   return true;
00195 }
00196 
00202 static void SubtractMoneyFromAnyCompany(Company *c, CommandCost cost)
00203 {
00204   if (cost.GetCost() == 0) return;
00205   assert(cost.GetExpensesType() != INVALID_EXPENSES);
00206 
00207   c->money -= cost.GetCost();
00208   c->yearly_expenses[0][cost.GetExpensesType()] += cost.GetCost();
00209 
00210   if (HasBit(1 << EXPENSES_TRAIN_INC    |
00211              1 << EXPENSES_ROADVEH_INC  |
00212              1 << EXPENSES_AIRCRAFT_INC |
00213              1 << EXPENSES_SHIP_INC, cost.GetExpensesType())) {
00214     c->cur_economy.income -= cost.GetCost();
00215   } else if (HasBit(1 << EXPENSES_TRAIN_RUN    |
00216                     1 << EXPENSES_ROADVEH_RUN  |
00217                     1 << EXPENSES_AIRCRAFT_RUN |
00218                     1 << EXPENSES_SHIP_RUN     |
00219                     1 << EXPENSES_PROPERTY     |
00220                     1 << EXPENSES_LOAN_INT, cost.GetExpensesType())) {
00221     c->cur_economy.expenses -= cost.GetCost();
00222   }
00223 
00224   InvalidateCompanyWindows(c);
00225 }
00226 
00231 void SubtractMoneyFromCompany(CommandCost cost)
00232 {
00233   Company *c = Company::GetIfValid(_current_company);
00234   if (c != NULL) SubtractMoneyFromAnyCompany(c, cost);
00235 }
00236 
00242 void SubtractMoneyFromCompanyFract(CompanyID company, CommandCost cst)
00243 {
00244   Company *c = Company::Get(company);
00245   byte m = c->money_fraction;
00246   Money cost = cst.GetCost();
00247 
00248   c->money_fraction = m - (byte)cost;
00249   cost >>= 8;
00250   if (c->money_fraction > m) cost++;
00251   if (cost != 0) SubtractMoneyFromAnyCompany(c, CommandCost(cst.GetExpensesType(), cost));
00252 }
00253 
00260 void GetNameOfOwner(Owner owner, TileIndex tile)
00261 {
00262   SetDParam(2, owner);
00263 
00264   if (owner != OWNER_TOWN) {
00265     if (!Company::IsValidID(owner)) {
00266       SetDParam(0, STR_COMPANY_SOMEONE);
00267     } else {
00268       SetDParam(0, STR_COMPANY_NAME);
00269       SetDParam(1, owner);
00270     }
00271   } else {
00272     assert(tile != 0);
00273     const Town *t = ClosestTownFromTile(tile, UINT_MAX);
00274 
00275     SetDParam(0, STR_TOWN_NAME);
00276     SetDParam(1, t->index);
00277   }
00278 }
00279 
00280 
00289 CommandCost CheckOwnership(Owner owner, TileIndex tile)
00290 {
00291   assert(owner < OWNER_END);
00292   assert(owner != OWNER_TOWN || tile != 0);
00293 
00294   if (owner == _current_company) return CommandCost();
00295 
00296   GetNameOfOwner(owner, tile);
00297   return_cmd_error(STR_ERROR_OWNED_BY);
00298 }
00299 
00307 CommandCost CheckTileOwnership(TileIndex tile)
00308 {
00309   Owner owner = GetTileOwner(tile);
00310 
00311   assert(owner < OWNER_END);
00312 
00313   if (owner == _current_company) return CommandCost();
00314 
00315   /* no need to get the name of the owner unless we're the local company (saves some time) */
00316   if (IsLocalCompany()) GetNameOfOwner(owner, tile);
00317   return_cmd_error(STR_ERROR_OWNED_BY);
00318 }
00319 
00324 static void GenerateCompanyName(Company *c)
00325 {
00326   /* Reserve space for extra unicode character. We need to do this to be able
00327    * to detect too long company name. */
00328   char buffer[(MAX_LENGTH_COMPANY_NAME_CHARS + 1) * MAX_CHAR_LENGTH];
00329 
00330   if (c->name_1 != STR_SV_UNNAMED) return;
00331   if (c->last_build_coordinate == 0) return;
00332 
00333   Town *t = ClosestTownFromTile(c->last_build_coordinate, UINT_MAX);
00334 
00335   StringID str;
00336   uint32 strp;
00337   if (t->name == NULL && IsInsideMM(t->townnametype, SPECSTR_TOWNNAME_START, SPECSTR_TOWNNAME_LAST + 1)) {
00338     str = t->townnametype - SPECSTR_TOWNNAME_START + SPECSTR_PLAYERNAME_START;
00339     strp = t->townnameparts;
00340 
00341 verify_name:;
00342     /* No companies must have this name already */
00343     Company *cc;
00344     FOR_ALL_COMPANIES(cc) {
00345       if (cc->name_1 == str && cc->name_2 == strp) goto bad_town_name;
00346     }
00347 
00348     GetString(buffer, str, lastof(buffer));
00349     if (Utf8StringLength(buffer) >= MAX_LENGTH_COMPANY_NAME_CHARS) goto bad_town_name;
00350 
00351 set_name:;
00352     c->name_1 = str;
00353     c->name_2 = strp;
00354 
00355     MarkWholeScreenDirty();
00356 
00357     if (c->is_ai) {
00358       CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
00359       cni->FillData(c);
00360       SetDParam(0, STR_NEWS_COMPANY_LAUNCH_TITLE);
00361       SetDParam(1, STR_NEWS_COMPANY_LAUNCH_DESCRIPTION);
00362       SetDParamStr(2, cni->company_name);
00363       SetDParam(3, t->index);
00364       AddNewsItem(STR_MESSAGE_NEWS_FORMAT, NS_COMPANY_NEW, NR_TILE, c->last_build_coordinate, NR_NONE, UINT32_MAX, cni);
00365     }
00366     AI::BroadcastNewEvent(new AIEventCompanyNew(c->index), c->index);
00367     return;
00368   }
00369 bad_town_name:;
00370 
00371   if (c->president_name_1 == SPECSTR_PRESIDENT_NAME) {
00372     str = SPECSTR_ANDCO_NAME;
00373     strp = c->president_name_2;
00374     goto set_name;
00375   } else {
00376     str = SPECSTR_ANDCO_NAME;
00377     strp = Random();
00378     goto verify_name;
00379   }
00380 }
00381 
00382 static const byte _colour_sort[COLOUR_END] = {2, 2, 3, 2, 3, 2, 3, 2, 3, 2, 2, 2, 3, 1, 1, 1};
00383 static const Colours _similar_colour[COLOUR_END][2] = {
00384   { COLOUR_BLUE,       COLOUR_LIGHT_BLUE }, // COLOUR_DARK_BLUE
00385   { COLOUR_GREEN,      COLOUR_DARK_GREEN }, // COLOUR_PALE_GREEN
00386   { INVALID_COLOUR,    INVALID_COLOUR    }, // COLOUR_PINK
00387   { COLOUR_ORANGE,     INVALID_COLOUR    }, // COLOUR_YELLOW
00388   { INVALID_COLOUR,    INVALID_COLOUR    }, // COLOUR_RED
00389   { COLOUR_DARK_BLUE,  COLOUR_BLUE       }, // COLOUR_LIGHT_BLUE
00390   { COLOUR_PALE_GREEN, COLOUR_DARK_GREEN }, // COLOUR_GREEN
00391   { COLOUR_PALE_GREEN, COLOUR_GREEN      }, // COLOUR_DARK_GREEN
00392   { COLOUR_DARK_BLUE,  COLOUR_LIGHT_BLUE }, // COLOUR_BLUE
00393   { COLOUR_BROWN,      COLOUR_ORANGE     }, // COLOUR_CREAM
00394   { COLOUR_PURPLE,     INVALID_COLOUR    }, // COLOUR_MAUVE
00395   { COLOUR_MAUVE,      INVALID_COLOUR    }, // COLOUR_PURPLE
00396   { COLOUR_YELLOW,     COLOUR_CREAM      }, // COLOUR_ORANGE
00397   { COLOUR_CREAM,      INVALID_COLOUR    }, // COLOUR_BROWN
00398   { COLOUR_WHITE,      INVALID_COLOUR    }, // COLOUR_GREY
00399   { COLOUR_GREY,       INVALID_COLOUR    }, // COLOUR_WHITE
00400 };
00401 
00406 static Colours GenerateCompanyColour()
00407 {
00408   Colours colours[COLOUR_END];
00409 
00410   /* Initialize array */
00411   for (uint i = 0; i < COLOUR_END; i++) colours[i] = (Colours)i;
00412 
00413   /* And randomize it */
00414   for (uint i = 0; i < 100; i++) {
00415     uint r = Random();
00416     Swap(colours[GB(r, 0, 4)], colours[GB(r, 4, 4)]);
00417   }
00418 
00419   /* Bubble sort it according to the values in table 1 */
00420   for (uint i = 0; i < COLOUR_END; i++) {
00421     for (uint j = 1; j < COLOUR_END; j++) {
00422       if (_colour_sort[colours[j - 1]] < _colour_sort[colours[j]]) {
00423         Swap(colours[j - 1], colours[j]);
00424       }
00425     }
00426   };
00427 
00428   /* Move the colours that look similar to each company's colour to the side */
00429   Company *c;
00430   FOR_ALL_COMPANIES(c) {
00431     Colours pcolour = (Colours)c->colour;
00432 
00433     for (uint i = 0; i < COLOUR_END; i++) {
00434       if (colours[i] == pcolour) {
00435         colours[i] = INVALID_COLOUR;
00436         break;
00437       }
00438     }
00439 
00440     for (uint j = 0; j < 2; j++) {
00441       Colours similar = _similar_colour[pcolour][j];
00442       if (similar == INVALID_COLOUR) break;
00443 
00444       for (uint i = 1; i < COLOUR_END; i++) {
00445         if (colours[i - 1] == similar) Swap(colours[i - 1], colours[i]);
00446       }
00447     }
00448   }
00449 
00450   /* Return the first available colour */
00451   for (uint i = 0; i < COLOUR_END; i++) {
00452     if (colours[i] != INVALID_COLOUR) return colours[i];
00453   }
00454 
00455   NOT_REACHED();
00456 }
00457 
00462 static void GeneratePresidentName(Company *c)
00463 {
00464   for (;;) {
00465 restart:;
00466     c->president_name_2 = Random();
00467     c->president_name_1 = SPECSTR_PRESIDENT_NAME;
00468 
00469     /* Reserve space for extra unicode character. We need to do this to be able
00470      * to detect too long president name. */
00471     char buffer[(MAX_LENGTH_PRESIDENT_NAME_CHARS + 1) * MAX_CHAR_LENGTH];
00472     SetDParam(0, c->index);
00473     GetString(buffer, STR_PRESIDENT_NAME, lastof(buffer));
00474     if (Utf8StringLength(buffer) >= MAX_LENGTH_PRESIDENT_NAME_CHARS) continue;
00475 
00476     Company *cc;
00477     FOR_ALL_COMPANIES(cc) {
00478       if (c != cc) {
00479         /* Reserve extra space so even overlength president names can be compared. */
00480         char buffer2[(MAX_LENGTH_PRESIDENT_NAME_CHARS + 1) * MAX_CHAR_LENGTH];
00481         SetDParam(0, cc->index);
00482         GetString(buffer2, STR_PRESIDENT_NAME, lastof(buffer2));
00483         if (strcmp(buffer2, buffer) == 0) goto restart;
00484       }
00485     }
00486     return;
00487   }
00488 }
00489 
00490 void ResetCompanyLivery(Company *c)
00491 {
00492   for (LiveryScheme scheme = LS_BEGIN; scheme < LS_END; scheme++) {
00493     c->livery[scheme].in_use  = false;
00494     c->livery[scheme].colour1 = c->colour;
00495     c->livery[scheme].colour2 = c->colour;
00496   }
00497 }
00498 
00506 Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY)
00507 {
00508   if (!Company::CanAllocateItem()) return NULL;
00509 
00510   /* we have to generate colour before this company is valid */
00511   Colours colour = GenerateCompanyColour();
00512 
00513   Company *c;
00514   if (company == INVALID_COMPANY) {
00515     c = new Company(STR_SV_UNNAMED, is_ai);
00516   } else {
00517     if (Company::IsValidID(company)) return NULL;
00518     c = new (company) Company(STR_SV_UNNAMED, is_ai);
00519   }
00520 
00521   c->colour = colour;
00522 
00523   ResetCompanyLivery(c);
00524   _company_colours[c->index] = (Colours)c->colour;
00525 
00526   c->money = c->current_loan = 100000;
00527 
00528   c->share_owners[0] = c->share_owners[1] = c->share_owners[2] = c->share_owners[3] = INVALID_OWNER;
00529 
00530   c->avail_railtypes = GetCompanyRailtypes(c->index);
00531   c->avail_roadtypes = GetCompanyRoadtypes(c->index);
00532   c->inaugurated_year = _cur_year;
00533   RandomCompanyManagerFaceBits(c->face, (GenderEthnicity)Random(), false); // create a random company manager face
00534 
00535   SetDefaultCompanySettings(c->index);
00536 
00537   GeneratePresidentName(c);
00538 
00539   SetWindowDirty(WC_GRAPH_LEGEND, 0);
00540   SetWindowDirty(WC_TOOLBAR_MENU, 0);
00541   SetWindowDirty(WC_CLIENT_LIST, 0);
00542 
00543   if (is_ai && (!_networking || _network_server)) AI::StartNew(c->index);
00544 
00545   c->num_engines = CallocT<uint16>(Engine::GetPoolSize());
00546 
00547   return c;
00548 }
00549 
00551 void StartupCompanies()
00552 {
00553   _next_competitor_start = 0;
00554 }
00555 
00556 #ifdef ENABLE_AI
00557 
00558 static void MaybeStartNewCompany()
00559 {
00560 #ifdef ENABLE_NETWORK
00561   if (_networking && Company::GetNumItems() >= _settings_client.network.max_companies) return;
00562 #endif /* ENABLE_NETWORK */
00563 
00564   Company *c;
00565 
00566   /* count number of competitors */
00567   uint n = 0;
00568   FOR_ALL_COMPANIES(c) {
00569     if (c->is_ai) n++;
00570   }
00571 
00572   if (n < (uint)_settings_game.difficulty.max_no_competitors) {
00573     /* Send a command to all clients to start up a new AI.
00574      * Works fine for Multiplayer and Singleplayer */
00575     DoCommandP(0, 1 | INVALID_COMPANY << 16, 0, CMD_COMPANY_CTRL);
00576   }
00577 }
00578 #endif /* ENABLE_AI */
00579 
00581 void InitializeCompanies()
00582 {
00583   _company_pool.CleanPool();
00584   _cur_company_tick_index = 0;
00585 }
00586 
00593 bool MayCompanyTakeOver(CompanyID cbig, CompanyID csmall)
00594 {
00595   uint big_counts[4], small_counts[4];
00596   CountCompanyVehicles(cbig,   big_counts);
00597   CountCompanyVehicles(csmall, small_counts);
00598 
00599   /* Do the combined vehicle counts stay within the limits? */
00600   return big_counts[VEH_TRAIN]     + small_counts[VEH_TRAIN]    <= _settings_game.vehicle.max_trains &&
00601     big_counts[VEH_ROAD]     + small_counts[VEH_ROAD]     <= _settings_game.vehicle.max_roadveh &&
00602     big_counts[VEH_SHIP]     + small_counts[VEH_SHIP]     <= _settings_game.vehicle.max_ships &&
00603     big_counts[VEH_AIRCRAFT] + small_counts[VEH_AIRCRAFT] <= _settings_game.vehicle.max_aircraft;
00604 }
00605 
00615 static void HandleBankruptcyTakeover(Company *c)
00616 {
00617   /* Amount of time out for each company to take over a company;
00618    * Timeout is a quarter (3 months of 30 days) divided over the
00619    * number of companies. The minimum number of days in a quarter
00620    * is 90: 31 in January, 28 in February and 31 in March.
00621    * Note that the company going bankrupt can't buy itself. */
00622   static const int TAKE_OVER_TIMEOUT = 3 * 30 * DAY_TICKS / (MAX_COMPANIES - 1);
00623 
00624   assert(c->bankrupt_asked != 0);
00625 
00626   /* We're currently asking some company to buy 'us' */
00627   if (c->bankrupt_timeout != 0) {
00628     c->bankrupt_timeout -= MAX_COMPANIES;
00629     if (c->bankrupt_timeout > 0) return;
00630     c->bankrupt_timeout = 0;
00631 
00632     return;
00633   }
00634 
00635   /* Did we ask everyone for bankruptcy? If so, bail out. */
00636   if (c->bankrupt_asked == MAX_UVALUE(CompanyMask)) return;
00637 
00638   Company *c2, *best = NULL;
00639   int32 best_performance = -1;
00640 
00641   /* Ask the company with the highest performance history first */
00642   FOR_ALL_COMPANIES(c2) {
00643     if (c2->bankrupt_asked == 0 && // Don't ask companies going bankrupt themselves
00644         !HasBit(c->bankrupt_asked, c2->index) &&
00645         best_performance < c2->old_economy[1].performance_history &&
00646         MayCompanyTakeOver(c2->index, c->index)) {
00647       best_performance = c2->old_economy[1].performance_history;
00648       best = c2;
00649     }
00650   }
00651 
00652   /* Asked all companies? */
00653   if (best_performance == -1) {
00654     c->bankrupt_asked = MAX_UVALUE(CompanyMask);
00655     return;
00656   }
00657 
00658   SetBit(c->bankrupt_asked, best->index);
00659 
00660   c->bankrupt_timeout = TAKE_OVER_TIMEOUT;
00661   if (best->is_ai) {
00662     AI::NewEvent(best->index, new AIEventCompanyAskMerger(c->index, ClampToI32(c->bankrupt_value)));
00663   } else if (IsInteractiveCompany(best->index)) {
00664     ShowBuyCompanyDialog(c->index);
00665   }
00666 }
00667 
00668 void OnTick_Companies()
00669 {
00670   if (_game_mode == GM_EDITOR) return;
00671 
00672   Company *c = Company::GetIfValid(_cur_company_tick_index);
00673   if (c != NULL) {
00674     if (c->name_1 != 0) GenerateCompanyName(c);
00675     if (c->bankrupt_asked != 0) HandleBankruptcyTakeover(c);
00676   }
00677 
00678 #ifdef ENABLE_AI
00679   if (_next_competitor_start == 0) {
00680     _next_competitor_start = AI::GetStartNextTime() * DAY_TICKS;
00681   }
00682 
00683   if (AI::CanStartNew() && _game_mode != GM_MENU && --_next_competitor_start == 0) {
00684     MaybeStartNewCompany();
00685   }
00686 #endif /* ENABLE_AI */
00687 
00688   _cur_company_tick_index = (_cur_company_tick_index + 1) % MAX_COMPANIES;
00689 }
00690 
00695 void CompaniesYearlyLoop()
00696 {
00697   Company *c;
00698 
00699   /* Copy statistics */
00700   FOR_ALL_COMPANIES(c) {
00701     memmove(&c->yearly_expenses[1], &c->yearly_expenses[0], sizeof(c->yearly_expenses) - sizeof(c->yearly_expenses[0]));
00702     memset(&c->yearly_expenses[0], 0, sizeof(c->yearly_expenses[0]));
00703     SetWindowDirty(WC_FINANCES, c->index);
00704   }
00705 
00706   if (_settings_client.gui.show_finances && _local_company != COMPANY_SPECTATOR) {
00707     ShowCompanyFinances(_local_company);
00708     c = Company::Get(_local_company);
00709     if (c->num_valid_stat_ent > 5 && c->old_economy[0].performance_history < c->old_economy[4].performance_history) {
00710       SndPlayFx(SND_01_BAD_YEAR);
00711     } else {
00712       SndPlayFx(SND_00_GOOD_YEAR);
00713     }
00714   }
00715 }
00716 
00722 void CompanyNewsInformation::FillData(const Company *c, const Company *other)
00723 {
00724   SetDParam(0, c->index);
00725   GetString(this->company_name, STR_COMPANY_NAME, lastof(this->company_name));
00726 
00727   if (other == NULL) {
00728     *this->other_company_name = '\0';
00729   } else {
00730     SetDParam(0, other->index);
00731     GetString(this->other_company_name, STR_COMPANY_NAME, lastof(this->other_company_name));
00732     c = other;
00733   }
00734 
00735   SetDParam(0, c->index);
00736   GetString(this->president_name, STR_PRESIDENT_NAME_MANAGER, lastof(this->president_name));
00737 
00738   this->colour = c->colour;
00739   this->face = c->face;
00740 
00741 }
00742 
00747 void CompanyAdminUpdate(const Company *company)
00748 {
00749 #ifdef ENABLE_NETWORK
00750   if (_network_server) NetworkAdminCompanyUpdate(company);
00751 #endif /* ENABLE_NETWORK */
00752 }
00753 
00758 void CompanyAdminBankrupt(CompanyID company_id)
00759 {
00760 #ifdef ENABLE_NETWORK
00761   if (_network_server) NetworkAdminCompanyRemove(company_id, ADMIN_CRR_BANKRUPT);
00762 #endif /* ENABLE_NETWORK */
00763 }
00764 
00779 CommandCost CmdCompanyCtrl(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00780 {
00781   InvalidateWindowData(WC_COMPANY_LEAGUE, 0, 0);
00782   CompanyID company_id = (CompanyID)GB(p1, 16, 8);
00783 #ifdef ENABLE_NETWORK
00784   ClientID client_id = (ClientID)p2;
00785 #endif /* ENABLE_NETWORK */
00786 
00787   switch (GB(p1, 0, 16)) {
00788     case 0: { // Create a new company
00789       /* This command is only executed in a multiplayer game */
00790       if (!_networking) return CMD_ERROR;
00791 
00792 #ifdef ENABLE_NETWORK
00793       /* Has the network client a correct ClientIndex? */
00794       if (!(flags & DC_EXEC)) return CommandCost();
00795       NetworkClientInfo *ci = NetworkFindClientInfoFromClientID(client_id);
00796       if (ci == NULL) return CommandCost();
00797 
00798       /* Delete multiplayer progress bar */
00799       DeleteWindowById(WC_NETWORK_STATUS_WINDOW, 0);
00800 
00801       Company *c = DoStartupNewCompany(false);
00802 
00803       /* A new company could not be created, revert to being a spectator */
00804       if (c == NULL) {
00805         if (_network_server) {
00806           ci->client_playas = COMPANY_SPECTATOR;
00807           NetworkUpdateClientInfo(ci->client_id);
00808         }
00809         break;
00810       }
00811 
00812       /* This is the client (or non-dedicated server) who wants a new company */
00813       if (client_id == _network_own_client_id) {
00814         assert(_local_company == COMPANY_SPECTATOR);
00815         SetLocalCompany(c->index);
00816         if (!StrEmpty(_settings_client.network.default_company_pass)) {
00817           NetworkChangeCompanyPassword(_settings_client.network.default_company_pass);
00818         }
00819 
00820         /* Now that we have a new company, broadcast our company settings to
00821          * all clients so everything is in sync */
00822         SyncCompanySettings();
00823 
00824         MarkWholeScreenDirty();
00825       }
00826 
00827       if (_network_server) {
00828         CompanyID old_playas = ci->client_playas;
00829         ci->client_playas = c->index;
00830         NetworkUpdateClientInfo(ci->client_id);
00831 
00832         if (Company::IsValidID(ci->client_playas)) {
00833           _network_company_states[c->index].months_empty = 0;
00834           _network_company_states[c->index].password[0] = '\0';
00835           NetworkServerUpdateCompanyPassworded(ci->client_playas, false);
00836 
00837           /* XXX - When a client joins, we automatically set its name to the
00838            * client's name (for some reason). As it stands now only the server
00839            * knows the client's name, so it needs to send out a "broadcast" to
00840            * do this. To achieve this we send a network command. However, it
00841            * uses _local_company to execute the command as.  To prevent abuse
00842            * (eg. only yourself can change your name/company), we 'cheat' by
00843            * impersonation _local_company as the server. Not the best solution;
00844            * but it works.
00845            * TODO: Perhaps this could be improved by when the client is ready
00846            * with joining to let it send itself the command, and not the server?
00847            * For example in network_client.c:534? */
00848           NetworkSendCommand(0, 0, 0, CMD_RENAME_PRESIDENT, NULL, ci->client_name, ci->client_playas);
00849         }
00850 
00851         /* Announce new company on network, if the client was a SPECTATOR before */
00852         if (old_playas == COMPANY_SPECTATOR) {
00853           NetworkAdminCompanyInfo(c, true);
00854           NetworkServerSendChat(NETWORK_ACTION_COMPANY_NEW, DESTTYPE_BROADCAST, 0, "", ci->client_id, ci->client_playas + 1);
00855         }
00856       }
00857 #endif /* ENABLE_NETWORK */
00858       break;
00859     }
00860 
00861     case 1: // Make a new AI company
00862       if (!(flags & DC_EXEC)) return CommandCost();
00863 
00864       if (company_id != INVALID_COMPANY && (company_id >= MAX_COMPANIES || Company::IsValidID(company_id))) return CMD_ERROR;
00865       DoStartupNewCompany(true, company_id);
00866       break;
00867 
00868     case 2: { // Delete a company
00869       Company *c = Company::GetIfValid(company_id);
00870       if (c == NULL) return CMD_ERROR;
00871 
00872       if (!(flags & DC_EXEC)) return CommandCost();
00873 
00874       /* Delete any open window of the company */
00875       DeleteCompanyWindows(c->index);
00876       CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
00877       cni->FillData(c);
00878 
00879       /* Show the bankrupt news */
00880       SetDParam(0, STR_NEWS_COMPANY_BANKRUPT_TITLE);
00881       SetDParam(1, STR_NEWS_COMPANY_BANKRUPT_DESCRIPTION);
00882       SetDParamStr(2, cni->company_name);
00883       AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, NS_COMPANY_BANKRUPT, cni);
00884 
00885       /* Remove the company */
00886       ChangeOwnershipOfCompanyItems(c->index, INVALID_OWNER);
00887       if (c->is_ai) AI::Stop(c->index);
00888 
00889       CompanyID c_index = c->index;
00890       delete c;
00891       AI::BroadcastNewEvent(new AIEventCompanyBankrupt(c_index));
00892       CompanyAdminBankrupt(c_index);
00893       break;
00894     }
00895 
00896     default: return CMD_ERROR;
00897   }
00898 
00899   return CommandCost();
00900 }
00901 
00911 CommandCost CmdSetCompanyManagerFace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00912 {
00913   CompanyManagerFace cmf = (CompanyManagerFace)p2;
00914 
00915   if (!IsValidCompanyManagerFace(cmf)) return CMD_ERROR;
00916 
00917   if (flags & DC_EXEC) {
00918     Company::Get(_current_company)->face = cmf;
00919     MarkWholeScreenDirty();
00920   }
00921   return CommandCost();
00922 }
00923 
00935 CommandCost CmdSetCompanyColour(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00936 {
00937   Colours colour = Extract<Colours, 0, 4>(p2);
00938   LiveryScheme scheme = Extract<LiveryScheme, 0, 8>(p1);
00939   byte state = GB(p1, 8, 2);
00940 
00941   if (scheme >= LS_END || state >= 3 || colour == INVALID_COLOUR) return CMD_ERROR;
00942 
00943   Company *c = Company::Get(_current_company);
00944 
00945   /* Ensure no two companies have the same primary colour */
00946   if (scheme == LS_DEFAULT && state == 0) {
00947     const Company *cc;
00948     FOR_ALL_COMPANIES(cc) {
00949       if (cc != c && cc->colour == colour) return CMD_ERROR;
00950     }
00951   }
00952 
00953   if (flags & DC_EXEC) {
00954     switch (state) {
00955       case 0:
00956         c->livery[scheme].colour1 = colour;
00957 
00958         /* If setting the first colour of the default scheme, adjust the
00959          * original and cached company colours too. */
00960         if (scheme == LS_DEFAULT) {
00961           _company_colours[_current_company] = colour;
00962           c->colour = colour;
00963           CompanyAdminUpdate(c);
00964         }
00965         break;
00966 
00967       case 1:
00968         c->livery[scheme].colour2 = colour;
00969         break;
00970 
00971       case 2:
00972         c->livery[scheme].in_use = colour != 0;
00973 
00974         /* Now handle setting the default scheme's in_use flag.
00975          * This is different to the other schemes, as it signifies if any
00976          * scheme is active at all. If this flag is not set, then no
00977          * processing of vehicle types occurs at all, and only the default
00978          * colours will be used. */
00979 
00980         /* If enabling a scheme, set the default scheme to be in use too */
00981         if (colour != 0) {
00982           c->livery[LS_DEFAULT].in_use = true;
00983           break;
00984         }
00985 
00986         /* Else loop through all schemes to see if any are left enabled.
00987          * If not, disable the default scheme too. */
00988         c->livery[LS_DEFAULT].in_use = false;
00989         for (scheme = LS_DEFAULT; scheme < LS_END; scheme++) {
00990           if (c->livery[scheme].in_use) {
00991             c->livery[LS_DEFAULT].in_use = true;
00992             break;
00993           }
00994         }
00995         break;
00996 
00997       default:
00998         break;
00999     }
01000     ResetVehicleColourMap();
01001     MarkWholeScreenDirty();
01002 
01003     /* All graph related to companies use the company colour. */
01004     InvalidateWindowData(WC_INCOME_GRAPH, 0);
01005     InvalidateWindowData(WC_OPERATING_PROFIT, 0);
01006     InvalidateWindowData(WC_DELIVERED_CARGO, 0);
01007     InvalidateWindowData(WC_PERFORMANCE_HISTORY, 0);
01008     InvalidateWindowData(WC_COMPANY_VALUE, 0);
01009 
01010     /* Company colour data is indirectly cached. */
01011     Vehicle *v;
01012     FOR_ALL_VEHICLES(v) {
01013       if (v->owner == _current_company) v->InvalidateNewGRFCache();
01014     }
01015 
01016     extern void UpdateObjectColours(const Company *c);
01017     UpdateObjectColours(c);
01018   }
01019   return CommandCost();
01020 }
01021 
01027 static bool IsUniqueCompanyName(const char *name)
01028 {
01029   const Company *c;
01030 
01031   FOR_ALL_COMPANIES(c) {
01032     if (c->name != NULL && strcmp(c->name, name) == 0) return false;
01033   }
01034 
01035   return true;
01036 }
01037 
01047 CommandCost CmdRenameCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01048 {
01049   bool reset = StrEmpty(text);
01050 
01051   if (!reset) {
01052     if (Utf8StringLength(text) >= MAX_LENGTH_COMPANY_NAME_CHARS) return CMD_ERROR;
01053     if (!IsUniqueCompanyName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
01054   }
01055 
01056   if (flags & DC_EXEC) {
01057     Company *c = Company::Get(_current_company);
01058     free(c->name);
01059     c->name = reset ? NULL : strdup(text);
01060     MarkWholeScreenDirty();
01061     CompanyAdminUpdate(c);
01062   }
01063 
01064   return CommandCost();
01065 }
01066 
01072 static bool IsUniquePresidentName(const char *name)
01073 {
01074   const Company *c;
01075 
01076   FOR_ALL_COMPANIES(c) {
01077     if (c->president_name != NULL && strcmp(c->president_name, name) == 0) return false;
01078   }
01079 
01080   return true;
01081 }
01082 
01092 CommandCost CmdRenamePresident(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01093 {
01094   bool reset = StrEmpty(text);
01095 
01096   if (!reset) {
01097     if (Utf8StringLength(text) >= MAX_LENGTH_PRESIDENT_NAME_CHARS) return CMD_ERROR;
01098     if (!IsUniquePresidentName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
01099   }
01100 
01101   if (flags & DC_EXEC) {
01102     Company *c = Company::Get(_current_company);
01103     free(c->president_name);
01104 
01105     if (reset) {
01106       c->president_name = NULL;
01107     } else {
01108       c->president_name = strdup(text);
01109 
01110       if (c->name_1 == STR_SV_UNNAMED && c->name == NULL) {
01111         char buf[80];
01112 
01113         snprintf(buf, lengthof(buf), "%s Transport", text);
01114         DoCommand(0, 0, 0, DC_EXEC, CMD_RENAME_COMPANY, buf);
01115       }
01116     }
01117 
01118     MarkWholeScreenDirty();
01119     CompanyAdminUpdate(c);
01120   }
01121 
01122   return CommandCost();
01123 }

Generated on Fri Dec 31 17:15:30 2010 for OpenTTD by  doxygen 1.6.1