town_cmd.cpp

Go to the documentation of this file.
00001 /* $Id: town_cmd.cpp 20494 2010-08-14 18:01:55Z 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 "road_internal.h" /* Cleaning up road bits */
00014 #include "road_cmd.h"
00015 #include "landscape.h"
00016 #include "viewport_func.h"
00017 #include "cmd_helper.h"
00018 #include "command_func.h"
00019 #include "industry.h"
00020 #include "station_base.h"
00021 #include "company_base.h"
00022 #include "news_func.h"
00023 #include "gui.h"
00024 #include "unmovable_map.h"
00025 #include "variables.h"
00026 #include "genworld.h"
00027 #include "newgrf.h"
00028 #include "newgrf_house.h"
00029 #include "newgrf_commons.h"
00030 #include "newgrf_text.h"
00031 #include "autoslope.h"
00032 #include "tunnelbridge_map.h"
00033 #include "unmovable_map.h"
00034 #include "strings_func.h"
00035 #include "window_func.h"
00036 #include "string_func.h"
00037 #include "newgrf_cargo.h"
00038 #include "cheat_type.h"
00039 #include "functions.h"
00040 #include "animated_tile_func.h"
00041 #include "date_func.h"
00042 #include "subsidy_func.h"
00043 #include "core/smallmap_type.hpp"
00044 #include "core/pool_func.hpp"
00045 #include "town.h"
00046 #include "townname_func.h"
00047 #include "townname_type.h"
00048 #include "core/random_func.hpp"
00049 
00050 #include "table/strings.h"
00051 #include "table/town_land.h"
00052 
00053 static Town *_cleared_town;
00054 static int _cleared_town_rating;
00055 TownID _new_town_id;
00056 
00057 /* Initialize the town-pool */
00058 TownPool _town_pool("Town");
00059 INSTANTIATE_POOL_METHODS(Town)
00060 
00061 Town::~Town()
00062 {
00063   free(this->name);
00064 
00065   if (CleaningPool()) return;
00066 
00067   Industry *i;
00068 
00069   /* Delete town authority window
00070    * and remove from list of sorted towns */
00071   DeleteWindowById(WC_TOWN_VIEW, this->index);
00072 
00073   /* Delete all industries belonging to the town */
00074   FOR_ALL_INDUSTRIES(i) if (i->town == this) delete i;
00075 
00076   /* Go through all tiles and delete those belonging to the town */
00077   for (TileIndex tile = 0; tile < MapSize(); ++tile) {
00078     switch (GetTileType(tile)) {
00079       case MP_HOUSE:
00080         if (Town::GetByTile(tile) == this) DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
00081         break;
00082 
00083       case MP_ROAD:
00084         /* Cached nearest town is updated later (after this town has been deleted) */
00085         if (HasTownOwnedRoad(tile) && GetTownIndex(tile) == this->index) {
00086           DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
00087         }
00088         break;
00089 
00090       case MP_TUNNELBRIDGE:
00091         if (IsTileOwner(tile, OWNER_TOWN) &&
00092             ClosestTownFromTile(tile, UINT_MAX) == this)
00093           DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
00094         break;
00095 
00096       case MP_UNMOVABLE:
00097         if (GetUnmovableType(tile) == UNMOVABLE_STATUE && GetStatueTownID(tile) == this->index) {
00098           DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
00099         }
00100         break;
00101 
00102       default:
00103         break;
00104     }
00105   }
00106 
00107   DeleteSubsidyWith(ST_TOWN, this->index);
00108   CargoPacket::InvalidateAllFrom(ST_TOWN, this->index);
00109   MarkWholeScreenDirty();
00110 }
00111 
00112 
00118 void Town::PostDestructor(size_t index)
00119 {
00120   InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
00121   UpdateNearestTownForRoadTiles(false);
00122 }
00123 
00127 void Town::InitializeLayout(TownLayout layout)
00128 {
00129   if (layout != TL_RANDOM) {
00130     this->layout = layout;
00131     return;
00132   }
00133 
00134   this->layout = TileHash(TileX(this->xy), TileY(this->xy)) % (NUM_TLS - 1);
00135 }
00136 
00141 /* static */ Town *Town::GetRandom()
00142 {
00143   if (Town::GetNumItems() == 0) return NULL;
00144   int num = RandomRange((uint16)Town::GetNumItems());
00145   size_t index = MAX_UVALUE(size_t);
00146 
00147   while (num >= 0) {
00148     num--;
00149     index++;
00150 
00151     /* Make sure we have a valid town */
00152     while (!Town::IsValidID(index)) {
00153       index++;
00154       assert(index < Town::GetPoolSize());
00155     }
00156   }
00157 
00158   return Town::Get(index);
00159 }
00160 
00161 Money HouseSpec::GetRemovalCost() const
00162 {
00163   return (_price[PR_CLEAR_HOUSE] * this->removal_cost) >> 8;
00164 }
00165 
00166 // Local
00167 static int _grow_town_result;
00168 
00169 /* Describe the possible states */
00170 enum TownGrowthResult {
00171   GROWTH_SUCCEED         = -1,
00172   GROWTH_SEARCH_STOPPED  =  0
00173 //  GROWTH_SEARCH_RUNNING >=  1
00174 };
00175 
00176 static bool BuildTownHouse(Town *t, TileIndex tile);
00177 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout);
00178 
00179 static void TownDrawHouseLift(const TileInfo *ti)
00180 {
00181   AddChildSpriteScreen(SPR_LIFT, PAL_NONE, 14, 60 - GetLiftPosition(ti->tile));
00182 }
00183 
00184 typedef void TownDrawTileProc(const TileInfo *ti);
00185 static TownDrawTileProc * const _town_draw_tile_procs[1] = {
00186   TownDrawHouseLift
00187 };
00188 
00194 static inline DiagDirection RandomDiagDir()
00195 {
00196   return (DiagDirection)(3 & Random());
00197 }
00198 
00204 static void DrawTile_Town(TileInfo *ti)
00205 {
00206   HouseID house_id = GetHouseType(ti->tile);
00207 
00208   if (house_id >= NEW_HOUSE_OFFSET) {
00209     /* Houses don't necessarily need new graphics. If they don't have a
00210      * spritegroup associated with them, then the sprite for the substitute
00211      * house id is drawn instead. */
00212     if (HouseSpec::Get(house_id)->spritegroup != NULL) {
00213       DrawNewHouseTile(ti, house_id);
00214       return;
00215     } else {
00216       house_id = HouseSpec::Get(house_id)->substitute_id;
00217     }
00218   }
00219 
00220   /* Retrieve pointer to the draw town tile struct */
00221   const DrawBuildingsTileStruct *dcts = &_town_draw_tile_data[house_id << 4 | TileHash2Bit(ti->x, ti->y) << 2 | GetHouseBuildingStage(ti->tile)];
00222 
00223   if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
00224 
00225   DrawGroundSprite(dcts->ground.sprite, dcts->ground.pal);
00226 
00227   /* If houses are invisible, do not draw the upper part */
00228   if (IsInvisibilitySet(TO_HOUSES)) return;
00229 
00230   /* Add a house on top of the ground? */
00231   SpriteID image = dcts->building.sprite;
00232   if (image != 0) {
00233     AddSortableSpriteToDraw(image, dcts->building.pal,
00234       ti->x + dcts->subtile_x,
00235       ti->y + dcts->subtile_y,
00236       dcts->width,
00237       dcts->height,
00238       dcts->dz,
00239       ti->z,
00240       IsTransparencySet(TO_HOUSES)
00241     );
00242 
00243     if (IsTransparencySet(TO_HOUSES)) return;
00244   }
00245 
00246   {
00247     int proc = dcts->draw_proc - 1;
00248 
00249     if (proc >= 0) _town_draw_tile_procs[proc](ti);
00250   }
00251 }
00252 
00253 static uint GetSlopeZ_Town(TileIndex tile, uint x, uint y)
00254 {
00255   return GetTileMaxZ(tile);
00256 }
00257 
00259 static Foundation GetFoundation_Town(TileIndex tile, Slope tileh)
00260 {
00261   HouseID hid = GetHouseType(tile);
00262 
00263   /* For NewGRF house tiles we might not be drawing a foundation. We need to
00264    * account for this, as other structures should
00265    * draw the wall of the foundation in this case.
00266    */
00267   if (hid >= NEW_HOUSE_OFFSET) {
00268     const HouseSpec *hs = HouseSpec::Get(hid);
00269     if (hs->spritegroup != NULL && HasBit(hs->callback_mask, CBM_HOUSE_DRAW_FOUNDATIONS)) {
00270       uint32 callback_res = GetHouseCallback(CBID_HOUSE_DRAW_FOUNDATIONS, 0, 0, hid, Town::GetByTile(tile), tile);
00271       if (callback_res == 0) return FOUNDATION_NONE;
00272     }
00273   }
00274   return FlatteningFoundation(tileh);
00275 }
00276 
00283 static void AnimateTile_Town(TileIndex tile)
00284 {
00285   if (GetHouseType(tile) >= NEW_HOUSE_OFFSET) {
00286     AnimateNewHouseTile(tile);
00287     return;
00288   }
00289 
00290   if (_tick_counter & 3) return;
00291 
00292   /* If the house is not one with a lift anymore, then stop this animating.
00293    * Not exactly sure when this happens, but probably when a house changes.
00294    * Before this was just a return...so it'd leak animated tiles..
00295    * That bug seems to have been here since day 1?? */
00296   if (!(HouseSpec::Get(GetHouseType(tile))->building_flags & BUILDING_IS_ANIMATED)) {
00297     DeleteAnimatedTile(tile);
00298     return;
00299   }
00300 
00301   if (!LiftHasDestination(tile)) {
00302     uint i;
00303 
00304     /* Building has 6 floors, number 0 .. 6, where 1 is illegal.
00305      * This is due to the fact that the first floor is, in the graphics,
00306      *  the height of 2 'normal' floors.
00307      * Furthermore, there are 6 lift positions from floor N (incl) to floor N + 1 (excl) */
00308     do {
00309       i = RandomRange(7);
00310     } while (i == 1 || i * 6 == GetLiftPosition(tile));
00311 
00312     SetLiftDestination(tile, i);
00313   }
00314 
00315   int pos = GetLiftPosition(tile);
00316   int dest = GetLiftDestination(tile) * 6;
00317   pos += (pos < dest) ? 1 : -1;
00318   SetLiftPosition(tile, pos);
00319 
00320   if (pos == dest) {
00321     HaltLift(tile);
00322     DeleteAnimatedTile(tile);
00323   }
00324 
00325   MarkTileDirtyByTile(tile);
00326 }
00327 
00334 static bool IsCloseToTown(TileIndex tile, uint dist)
00335 {
00336   const Town *t;
00337 
00338   FOR_ALL_TOWNS(t) {
00339     if (DistanceManhattan(tile, t->xy) < dist) return true;
00340   }
00341   return false;
00342 }
00343 
00348 void Town::UpdateVirtCoord()
00349 {
00350   Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
00351   SetDParam(0, this->index);
00352   SetDParam(1, this->population);
00353   this->sign.UpdatePosition(pt.x, pt.y - 24,
00354     _settings_client.gui.population_in_label ? STR_VIEWPORT_TOWN_POP : STR_VIEWPORT_TOWN);
00355 
00356   SetWindowDirty(WC_TOWN_VIEW, this->index);
00357 }
00358 
00360 void UpdateAllTownVirtCoords()
00361 {
00362   Town *t;
00363 
00364   FOR_ALL_TOWNS(t) {
00365     t->UpdateVirtCoord();
00366   }
00367 }
00368 
00374 static void ChangePopulation(Town *t, int mod)
00375 {
00376   t->population += mod;
00377   SetWindowDirty(WC_TOWN_VIEW, t->index);
00378   t->UpdateVirtCoord();
00379 
00380   InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
00381 }
00382 
00388 uint32 GetWorldPopulation()
00389 {
00390   uint32 pop = 0;
00391   const Town *t;
00392 
00393   FOR_ALL_TOWNS(t) pop += t->population;
00394   return pop;
00395 }
00396 
00401 static void MakeSingleHouseBigger(TileIndex tile)
00402 {
00403   assert(IsTileType(tile, MP_HOUSE));
00404 
00405   /* means it is completed, get out. */
00406   if (LiftHasDestination(tile)) return;
00407 
00408   /* progress in construction stages */
00409   IncHouseConstructionTick(tile);
00410   if (GetHouseConstructionTick(tile) != 0) return;
00411 
00412   const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
00413 
00414   /* Check and/or  */
00415   if (HasBit(hs->callback_mask, CBM_HOUSE_CONSTRUCTION_STATE_CHANGE)) {
00416     uint16 callback_res = GetHouseCallback(CBID_HOUSE_CONSTRUCTION_STATE_CHANGE, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
00417     if (callback_res != CALLBACK_FAILED) ChangeHouseAnimationFrame(hs->grffile, tile, callback_res);
00418   }
00419 
00420   if (IsHouseCompleted(tile)) {
00421     /* Now that construction is complete, we can add the population of the
00422      * building to the town. */
00423     ChangePopulation(Town::GetByTile(tile), hs->population);
00424     ResetHouseAge(tile);
00425   }
00426   MarkTileDirtyByTile(tile);
00427 }
00428 
00432 static void MakeTownHouseBigger(TileIndex tile)
00433 {
00434   uint flags = HouseSpec::Get(GetHouseType(tile))->building_flags;
00435   if (flags & BUILDING_HAS_1_TILE)  MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 0));
00436   if (flags & BUILDING_2_TILES_Y)   MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 1));
00437   if (flags & BUILDING_2_TILES_X)   MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 0));
00438   if (flags & BUILDING_HAS_4_TILES) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 1));
00439 }
00440 
00447 static void TileLoop_Town(TileIndex tile)
00448 {
00449   HouseID house_id = GetHouseType(tile);
00450 
00451   /* NewHouseTileLoop returns false if Callback 21 succeeded, i.e. the house
00452    * doesn't exist any more, so don't continue here. */
00453   if (house_id >= NEW_HOUSE_OFFSET && !NewHouseTileLoop(tile)) return;
00454 
00455   if (!IsHouseCompleted(tile)) {
00456     /* Construction is not completed. See if we can go further in construction*/
00457     MakeTownHouseBigger(tile);
00458     return;
00459   }
00460 
00461   const HouseSpec *hs = HouseSpec::Get(house_id);
00462 
00463   /* If the lift has a destination, it is already an animated tile. */
00464   if ((hs->building_flags & BUILDING_IS_ANIMATED) &&
00465       house_id < NEW_HOUSE_OFFSET &&
00466       !LiftHasDestination(tile) &&
00467       Chance16(1, 2)) {
00468     AddAnimatedTile(tile);
00469   }
00470 
00471   Town *t = Town::GetByTile(tile);
00472   uint32 r = Random();
00473 
00474   StationFinder stations(TileArea(tile, 1, 1));
00475 
00476   if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
00477     for (uint i = 0; i < 256; i++) {
00478       uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, r, house_id, t, tile);
00479 
00480       if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
00481 
00482       CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grffile);
00483       if (cargo == CT_INVALID) continue;
00484 
00485       uint amt = GB(callback, 0, 8);
00486       if (amt == 0) continue;
00487 
00488       uint moved = MoveGoodsToStation(cargo, amt, ST_TOWN, t->index, stations.GetStations());
00489 
00490       const CargoSpec *cs = CargoSpec::Get(cargo);
00491       switch (cs->town_effect) {
00492         case TE_PASSENGERS:
00493           t->new_max_pass += amt;
00494           t->new_act_pass += moved;
00495           break;
00496 
00497         case TE_MAIL:
00498           t->new_max_mail += amt;
00499           t->new_act_mail += moved;
00500           break;
00501 
00502         default:
00503           break;
00504       }
00505     }
00506   } else {
00507     if (GB(r, 0, 8) < hs->population) {
00508       uint amt = GB(r, 0, 8) / 8 + 1;
00509 
00510       if (_economy.fluct <= 0) amt = (amt + 1) >> 1;
00511       t->new_max_pass += amt;
00512       t->new_act_pass += MoveGoodsToStation(CT_PASSENGERS, amt, ST_TOWN, t->index, stations.GetStations());
00513     }
00514 
00515     if (GB(r, 8, 8) < hs->mail_generation) {
00516       uint amt = GB(r, 8, 8) / 8 + 1;
00517 
00518       if (_economy.fluct <= 0) amt = (amt + 1) >> 1;
00519       t->new_max_mail += amt;
00520       t->new_act_mail += MoveGoodsToStation(CT_MAIL, amt, ST_TOWN, t->index, stations.GetStations());
00521     }
00522   }
00523 
00524   _current_company = OWNER_TOWN;
00525 
00526   if ((hs->building_flags & BUILDING_HAS_1_TILE) &&
00527       HasBit(t->flags, TOWN_IS_FUNDED) &&
00528       CanDeleteHouse(tile) &&
00529       GetHouseAge(tile) >= hs->minimum_life &&
00530       --t->time_until_rebuild == 0) {
00531     t->time_until_rebuild = GB(r, 16, 8) + 192;
00532 
00533     ClearTownHouse(t, tile);
00534 
00535     /* Rebuild with another house? */
00536     if (GB(r, 24, 8) >= 12) BuildTownHouse(t, tile);
00537   }
00538 
00539   _current_company = OWNER_NONE;
00540 }
00541 
00542 static CommandCost ClearTile_Town(TileIndex tile, DoCommandFlag flags)
00543 {
00544   if (flags & DC_AUTO) return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
00545   if (!CanDeleteHouse(tile)) return CMD_ERROR;
00546 
00547   const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
00548 
00549   CommandCost cost(EXPENSES_CONSTRUCTION);
00550   cost.AddCost(hs->GetRemovalCost());
00551 
00552   int rating = hs->remove_rating_decrease;
00553   _cleared_town_rating += rating;
00554   Town *t = _cleared_town = Town::GetByTile(tile);
00555 
00556   if (Company::IsValidID(_current_company)) {
00557     if (rating > t->ratings[_current_company] && !(flags & DC_NO_TEST_TOWN_RATING) && !_cheats.magic_bulldozer.value) {
00558       SetDParam(0, t->index);
00559       return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
00560     }
00561   }
00562 
00563   ChangeTownRating(t, -rating, RATING_HOUSE_MINIMUM, flags);
00564   if (flags & DC_EXEC) {
00565     ClearTownHouse(t, tile);
00566   }
00567 
00568   return cost;
00569 }
00570 
00571 static void AddProducedCargo_Town(TileIndex tile, CargoArray &produced)
00572 {
00573   HouseID house_id = GetHouseType(tile);
00574   const HouseSpec *hs = HouseSpec::Get(house_id);
00575   Town *t = Town::GetByTile(tile);
00576 
00577   if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
00578     for (uint i = 0; i < 256; i++) {
00579       uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, 0, house_id, t, tile);
00580 
00581       if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
00582 
00583       CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grffile);
00584 
00585       if (cargo == CT_INVALID) continue;
00586       produced[cargo]++;
00587     }
00588   } else {
00589     if (hs->population > 0) {
00590       produced[CT_PASSENGERS]++;
00591     }
00592     if (hs->mail_generation > 0) {
00593       produced[CT_MAIL]++;
00594     }
00595   }
00596 }
00597 
00598 static inline void AddAcceptedCargoSetMask(CargoID cargo, uint amount, CargoArray &acceptance, uint32 *always_accepted)
00599 {
00600   if (cargo == CT_INVALID || amount == 0) return;
00601   acceptance[cargo] += amount;
00602   SetBit(*always_accepted, cargo);
00603 }
00604 
00605 static void AddAcceptedCargo_Town(TileIndex tile, CargoArray &acceptance, uint32 *always_accepted)
00606 {
00607   const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
00608   CargoID accepts[3];
00609 
00610   /* Set the initial accepted cargo types */
00611   for (uint8 i = 0; i < lengthof(accepts); i++) {
00612     accepts[i] = hs->accepts_cargo[i];
00613   }
00614 
00615   /* Check for custom accepted cargo types */
00616   if (HasBit(hs->callback_mask, CBM_HOUSE_ACCEPT_CARGO)) {
00617     uint16 callback = GetHouseCallback(CBID_HOUSE_ACCEPT_CARGO, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
00618     if (callback != CALLBACK_FAILED) {
00619       /* Replace accepted cargo types with translated values from callback */
00620       accepts[0] = GetCargoTranslation(GB(callback,  0, 5), hs->grffile);
00621       accepts[1] = GetCargoTranslation(GB(callback,  5, 5), hs->grffile);
00622       accepts[2] = GetCargoTranslation(GB(callback, 10, 5), hs->grffile);
00623     }
00624   }
00625 
00626   /* Check for custom cargo acceptance */
00627   if (HasBit(hs->callback_mask, CBM_HOUSE_CARGO_ACCEPTANCE)) {
00628     uint16 callback = GetHouseCallback(CBID_HOUSE_CARGO_ACCEPTANCE, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
00629     if (callback != CALLBACK_FAILED) {
00630       AddAcceptedCargoSetMask(accepts[0], GB(callback, 0, 4), acceptance, always_accepted);
00631       AddAcceptedCargoSetMask(accepts[1], GB(callback, 4, 4), acceptance, always_accepted);
00632       if (_settings_game.game_creation.landscape != LT_TEMPERATE && HasBit(callback, 12)) {
00633         /* The 'S' bit indicates food instead of goods */
00634         AddAcceptedCargoSetMask(CT_FOOD, GB(callback, 8, 4), acceptance, always_accepted);
00635       } else {
00636         AddAcceptedCargoSetMask(accepts[2], GB(callback, 8, 4), acceptance, always_accepted);
00637       }
00638       return;
00639     }
00640   }
00641 
00642   /* No custom acceptance, so fill in with the default values */
00643   for (uint8 i = 0; i < lengthof(accepts); i++) {
00644     AddAcceptedCargoSetMask(accepts[i], hs->cargo_acceptance[i], acceptance, always_accepted);
00645   }
00646 }
00647 
00648 static void GetTileDesc_Town(TileIndex tile, TileDesc *td)
00649 {
00650   const HouseID house = GetHouseType(tile);
00651   const HouseSpec *hs = HouseSpec::Get(house);
00652   bool house_completed = IsHouseCompleted(tile);
00653 
00654   td->str = hs->building_name;
00655 
00656   uint16 callback_res = GetHouseCallback(CBID_HOUSE_CUSTOM_NAME, house_completed ? 1 : 0, 0, house, Town::GetByTile(tile), tile);
00657   if (callback_res != CALLBACK_FAILED) {
00658     StringID new_name = GetGRFStringID(hs->grffile->grfid, 0xD000 + callback_res);
00659     if (new_name != STR_NULL && new_name != STR_UNDEFINED) {
00660       td->str = new_name;
00661     }
00662   }
00663 
00664   if (!house_completed) {
00665     SetDParamX(td->dparam, 0, td->str);
00666     td->str = STR_LAI_TOWN_INDUSTRY_DESCRIPTION_UNDER_CONSTRUCTION;
00667   }
00668 
00669   if (hs->grffile != NULL) {
00670     const GRFConfig *gc = GetGRFConfig(hs->grffile->grfid);
00671     td->grf = gc->name;
00672   }
00673 
00674   td->owner[0] = OWNER_TOWN;
00675 }
00676 
00677 static TrackStatus GetTileTrackStatus_Town(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
00678 {
00679   /* not used */
00680   return 0;
00681 }
00682 
00683 static void ChangeTileOwner_Town(TileIndex tile, Owner old_owner, Owner new_owner)
00684 {
00685   /* not used */
00686 }
00687 
00688 static bool GrowTown(Town *t);
00689 
00690 static void TownTickHandler(Town *t)
00691 {
00692   if (HasBit(t->flags, TOWN_IS_FUNDED)) {
00693     int i = t->grow_counter - 1;
00694     if (i < 0) {
00695       if (GrowTown(t)) {
00696         i = t->growth_rate;
00697       } else {
00698         i = 0;
00699       }
00700     }
00701     t->grow_counter = i;
00702   }
00703 
00704   UpdateTownRadius(t);
00705 }
00706 
00707 void OnTick_Town()
00708 {
00709   if (_game_mode == GM_EDITOR) return;
00710 
00711   Town *t;
00712   FOR_ALL_TOWNS(t) {
00713     /* Run town tick at regular intervals, but not all at once. */
00714     if ((_tick_counter + t->index) % TOWN_GROWTH_FREQUENCY == 0) {
00715       TownTickHandler(t);
00716     }
00717   }
00718 }
00719 
00728 static RoadBits GetTownRoadBits(TileIndex tile)
00729 {
00730   if (IsRoadDepotTile(tile) || IsStandardRoadStopTile(tile)) return ROAD_NONE;
00731 
00732   return GetAnyRoadBits(tile, ROADTYPE_ROAD, true);
00733 }
00734 
00745 static bool IsNeighborRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
00746 {
00747   if (!IsValidTile(tile)) return false;
00748 
00749   /* Lookup table for the used diff values */
00750   const TileIndexDiff tid_lt[3] = {
00751     TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90RIGHT)),
00752     TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90LEFT)),
00753     TileOffsByDiagDir(ReverseDiagDir(dir)),
00754   };
00755 
00756   dist_multi = (dist_multi + 1) * 4;
00757   for (uint pos = 4; pos < dist_multi; pos++) {
00758     /* Go (pos / 4) tiles to the left or the right */
00759     TileIndexDiff cur = tid_lt[(pos & 1) ? 0 : 1] * (pos / 4);
00760 
00761     /* Use the current tile as origin, or go one tile backwards */
00762     if (pos & 2) cur += tid_lt[2];
00763 
00764     /* Test for roadbit parallel to dir and facing towards the middle axis */
00765     if (IsValidTile(tile + cur) &&
00766       GetTownRoadBits(TILE_ADD(tile, cur)) & DiagDirToRoadBits((pos & 2) ? dir : ReverseDiagDir(dir))) return true;
00767   }
00768   return false;
00769 }
00770 
00779 static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
00780 {
00781   if (DistanceFromEdge(tile) == 0) return false;
00782 
00783   Slope cur_slope, desired_slope;
00784 
00785   for (;;) {
00786     /* Check if there already is a road at this point? */
00787     if (GetTownRoadBits(tile) == ROAD_NONE) {
00788       /* No, try if we are able to build a road piece there.
00789        * If that fails clear the land, and if that fails exit.
00790        * This is to make sure that we can build a road here later. */
00791       if (DoCommand(tile, ((dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? ROAD_X : ROAD_Y), 0, DC_AUTO, CMD_BUILD_ROAD).Failed() &&
00792           DoCommand(tile, 0, 0, DC_AUTO, CMD_LANDSCAPE_CLEAR).Failed())
00793         return false;
00794     }
00795 
00796     cur_slope = _settings_game.construction.build_on_slopes ? GetFoundationSlope(tile, NULL) : GetTileSlope(tile, NULL);
00797     bool ret = !IsNeighborRoadTile(tile, dir, t->layout == TL_ORIGINAL ? 1 : 2);
00798     if (cur_slope == SLOPE_FLAT) return ret;
00799 
00800     /* If the tile is not a slope in the right direction, then
00801      * maybe terraform some. */
00802     desired_slope = (dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? SLOPE_NW : SLOPE_NE;
00803     if (desired_slope != cur_slope && ComplementSlope(desired_slope) != cur_slope) {
00804       if (Chance16(1, 8)) {
00805         CommandCost res = CMD_ERROR;
00806         if (!_generating_world && Chance16(1, 10)) {
00807           /* Note: Do not replace "^ SLOPE_ELEVATED" with ComplementSlope(). The slope might be steep. */
00808           res = DoCommand(tile, Chance16(1, 16) ? cur_slope : cur_slope ^ SLOPE_ELEVATED, 0,
00809               DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
00810         }
00811         if (res.Failed() && Chance16(1, 3)) {
00812           /* We can consider building on the slope, though. */
00813           return ret;
00814         }
00815       }
00816       return false;
00817     }
00818     return ret;
00819   }
00820 }
00821 
00822 static bool TerraformTownTile(TileIndex tile, int edges, int dir)
00823 {
00824   assert(tile < MapSize());
00825 
00826   CommandCost r = DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
00827   if (r.Failed() || r.GetCost() >= (_price[PR_TERRAFORM] + 2) * 8) return false;
00828   DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER | DC_EXEC, CMD_TERRAFORM_LAND);
00829   return true;
00830 }
00831 
00832 static void LevelTownLand(TileIndex tile)
00833 {
00834   assert(tile < MapSize());
00835 
00836   /* Don't terraform if land is plain or if there's a house there. */
00837   if (IsTileType(tile, MP_HOUSE)) return;
00838   Slope tileh = GetTileSlope(tile, NULL);
00839   if (tileh == SLOPE_FLAT) return;
00840 
00841   /* First try up, then down */
00842   if (!TerraformTownTile(tile, ~tileh & SLOPE_ELEVATED, 1)) {
00843     TerraformTownTile(tile, tileh & SLOPE_ELEVATED, 0);
00844   }
00845 }
00846 
00856 static RoadBits GetTownRoadGridElement(Town *t, TileIndex tile, DiagDirection dir)
00857 {
00858   /* align the grid to the downtown */
00859   TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile); // Vector from downtown to the tile
00860   RoadBits rcmd = ROAD_NONE;
00861 
00862   switch (t->layout) {
00863     default: NOT_REACHED();
00864 
00865     case TL_2X2_GRID:
00866       if ((grid_pos.x % 3) == 0) rcmd |= ROAD_Y;
00867       if ((grid_pos.y % 3) == 0) rcmd |= ROAD_X;
00868       break;
00869 
00870     case TL_3X3_GRID:
00871       if ((grid_pos.x % 4) == 0) rcmd |= ROAD_Y;
00872       if ((grid_pos.y % 4) == 0) rcmd |= ROAD_X;
00873       break;
00874   }
00875 
00876   /* Optimise only X-junctions */
00877   if (rcmd != ROAD_ALL) return rcmd;
00878 
00879   RoadBits rb_template;
00880 
00881   switch (GetTileSlope(tile, NULL)) {
00882     default:       rb_template = ROAD_ALL; break;
00883     case SLOPE_W:  rb_template = ROAD_NW | ROAD_SW; break;
00884     case SLOPE_SW: rb_template = ROAD_Y  | ROAD_SW; break;
00885     case SLOPE_S:  rb_template = ROAD_SW | ROAD_SE; break;
00886     case SLOPE_SE: rb_template = ROAD_X  | ROAD_SE; break;
00887     case SLOPE_E:  rb_template = ROAD_SE | ROAD_NE; break;
00888     case SLOPE_NE: rb_template = ROAD_Y  | ROAD_NE; break;
00889     case SLOPE_N:  rb_template = ROAD_NE | ROAD_NW; break;
00890     case SLOPE_NW: rb_template = ROAD_X  | ROAD_NW; break;
00891     case SLOPE_STEEP_W:
00892     case SLOPE_STEEP_S:
00893     case SLOPE_STEEP_E:
00894     case SLOPE_STEEP_N:
00895       rb_template = ROAD_NONE;
00896       break;
00897   }
00898 
00899   /* Stop if the template is compatible to the growth dir */
00900   if (DiagDirToRoadBits(ReverseDiagDir(dir)) & rb_template) return rb_template;
00901   /* If not generate a straight road in the direction of the growth */
00902   return DiagDirToRoadBits(dir) | DiagDirToRoadBits(ReverseDiagDir(dir));
00903 }
00904 
00915 static bool GrowTownWithExtraHouse(Town *t, TileIndex tile)
00916 {
00917   /* We can't look further than that. */
00918   if (DistanceFromEdge(tile) == 0) return false;
00919 
00920   uint counter = 0; // counts the house neighbor tiles
00921 
00922   /* Check the tiles E,N,W and S of the current tile for houses */
00923   for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
00924     /* Count both void and house tiles for checking whether there
00925      * are enough houses in the area. This to make it likely that
00926      * houses get build up to the edge of the map. */
00927     switch (GetTileType(TileAddByDiagDir(tile, dir))) {
00928       case MP_HOUSE:
00929       case MP_VOID:
00930         counter++;
00931         break;
00932 
00933       default:
00934         break;
00935     }
00936 
00937     /* If there are enough neighbors stop here */
00938     if (counter >= 3) {
00939       if (BuildTownHouse(t, tile)) {
00940         _grow_town_result = GROWTH_SUCCEED;
00941         return true;
00942       }
00943       return false;
00944     }
00945   }
00946   return false;
00947 }
00948 
00957 static bool GrowTownWithRoad(const Town *t, TileIndex tile, RoadBits rcmd)
00958 {
00959   if (DoCommand(tile, rcmd, t->index, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD).Succeeded()) {
00960     _grow_town_result = GROWTH_SUCCEED;
00961     return true;
00962   }
00963   return false;
00964 }
00965 
00976 static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
00977 {
00978   assert(bridge_dir < DIAGDIR_END);
00979 
00980   const Slope slope = GetTileSlope(tile, NULL);
00981   if (slope == SLOPE_FLAT) return false; // no slope, no bridge
00982 
00983   /* Make sure the direction is compatible with the slope.
00984    * Well we check if the slope has an up bit set in the
00985    * reverse direction. */
00986   if (slope & InclinedSlope(bridge_dir)) return false;
00987 
00988   /* Assure that the bridge is connectable to the start side */
00989   if (!(GetTownRoadBits(TileAddByDiagDir(tile, ReverseDiagDir(bridge_dir))) & DiagDirToRoadBits(bridge_dir))) return false;
00990 
00991   /* We are in the right direction */
00992   uint8 bridge_length = 0;      // This value stores the length of the possible bridge
00993   TileIndex bridge_tile = tile; // Used to store the other waterside
00994 
00995   const int delta = TileOffsByDiagDir(bridge_dir);
00996   do {
00997     if (bridge_length++ >= 11) {
00998       /* Max 11 tile long bridges */
00999       return false;
01000     }
01001     bridge_tile += delta;
01002   } while (TileX(bridge_tile) != 0 && TileY(bridge_tile) != 0 && IsWaterTile(bridge_tile));
01003 
01004   /* no water tiles in between? */
01005   if (bridge_length == 1) return false;
01006 
01007   for (uint8 times = 0; times <= 22; times++) {
01008     byte bridge_type = RandomRange(MAX_BRIDGES - 1);
01009 
01010     /* Can we actually build the bridge? */
01011     if (DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, DC_AUTO, CMD_BUILD_BRIDGE).Succeeded()) {
01012       DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, DC_EXEC | DC_AUTO, CMD_BUILD_BRIDGE);
01013       _grow_town_result = GROWTH_SUCCEED;
01014       return true;
01015     }
01016   }
01017   /* Quit if it selecting an appropiate bridge type fails a large number of times. */
01018   return false;
01019 }
01020 
01038 static void GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1)
01039 {
01040   RoadBits rcmd = ROAD_NONE;  // RoadBits for the road construction command
01041   TileIndex tile = *tile_ptr; // The main tile on which we base our growth
01042 
01043   assert(tile < MapSize());
01044 
01045   if (cur_rb == ROAD_NONE) {
01046     /* Tile has no road. First reset the status counter
01047      * to say that this is the last iteration. */
01048     _grow_town_result = GROWTH_SEARCH_STOPPED;
01049 
01050     if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
01051 
01052     /* Remove hills etc */
01053     if (!_settings_game.construction.build_on_slopes || Chance16(1, 6)) LevelTownLand(tile);
01054 
01055     /* Is a road allowed here? */
01056     switch (t1->layout) {
01057       default: NOT_REACHED();
01058 
01059       case TL_3X3_GRID:
01060       case TL_2X2_GRID:
01061         rcmd = GetTownRoadGridElement(t1, tile, target_dir);
01062         if (rcmd == ROAD_NONE) return;
01063         break;
01064 
01065       case TL_BETTER_ROADS:
01066       case TL_ORIGINAL:
01067         if (!IsRoadAllowedHere(t1, tile, target_dir)) return;
01068 
01069         DiagDirection source_dir = ReverseDiagDir(target_dir);
01070 
01071         if (Chance16(1, 4)) {
01072           /* Randomize a new target dir */
01073           do target_dir = RandomDiagDir(); while (target_dir == source_dir);
01074         }
01075 
01076         if (!IsRoadAllowedHere(t1, TileAddByDiagDir(tile, target_dir), target_dir)) {
01077           /* A road is not allowed to continue the randomized road,
01078            *  return if the road we're trying to build is curved. */
01079           if (target_dir != ReverseDiagDir(source_dir)) return;
01080 
01081           /* Return if neither side of the new road is a house */
01082           if (!IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90RIGHT)), MP_HOUSE) &&
01083               !IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90LEFT)), MP_HOUSE)) {
01084             return;
01085           }
01086 
01087           /* That means that the road is only allowed if there is a house
01088            *  at any side of the new road. */
01089         }
01090 
01091         rcmd = DiagDirToRoadBits(target_dir) | DiagDirToRoadBits(source_dir);
01092         break;
01093     }
01094 
01095   } else if (target_dir < DIAGDIR_END && !(cur_rb & DiagDirToRoadBits(ReverseDiagDir(target_dir)))) {
01096     /* Continue building on a partial road.
01097      * Should be allways OK, so we only generate
01098      * the fitting RoadBits */
01099     _grow_town_result = GROWTH_SEARCH_STOPPED;
01100 
01101     if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
01102 
01103     switch (t1->layout) {
01104       default: NOT_REACHED();
01105 
01106       case TL_3X3_GRID:
01107       case TL_2X2_GRID:
01108         rcmd = GetTownRoadGridElement(t1, tile, target_dir);
01109         break;
01110 
01111       case TL_BETTER_ROADS:
01112       case TL_ORIGINAL:
01113         rcmd = DiagDirToRoadBits(ReverseDiagDir(target_dir));
01114         break;
01115     }
01116   } else {
01117     bool allow_house = true; // Value which decides if we want to construct a house
01118 
01119     /* Reached a tunnel/bridge? Then continue at the other side of it. */
01120     if (IsTileType(tile, MP_TUNNELBRIDGE)) {
01121       if (GetTunnelBridgeTransportType(tile) == TRANSPORT_ROAD) {
01122         *tile_ptr = GetOtherTunnelBridgeEnd(tile);
01123       }
01124       return;
01125     }
01126 
01127     /* Possibly extend the road in a direction.
01128      * Randomize a direction and if it has a road, bail out. */
01129     target_dir = RandomDiagDir();
01130     if (cur_rb & DiagDirToRoadBits(target_dir)) return;
01131 
01132     /* This is the tile we will reach if we extend to this direction. */
01133     TileIndex house_tile = TileAddByDiagDir(tile, target_dir); // position of a possible house
01134 
01135     /* Don't walk into water. */
01136     if (IsWaterTile(house_tile)) return;
01137 
01138     if (!IsValidTile(house_tile)) return;
01139 
01140     if (_settings_game.economy.allow_town_roads || _generating_world) {
01141       switch (t1->layout) {
01142         default: NOT_REACHED();
01143 
01144         case TL_3X3_GRID: // Use 2x2 grid afterwards!
01145           GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
01146           /* FALL THROUGH */
01147 
01148         case TL_2X2_GRID:
01149           rcmd = GetTownRoadGridElement(t1, house_tile, target_dir);
01150           allow_house = (rcmd == ROAD_NONE);
01151           break;
01152 
01153         case TL_BETTER_ROADS: // Use original afterwards!
01154           GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
01155           /* FALL THROUGH */
01156 
01157         case TL_ORIGINAL:
01158           /* Allow a house at the edge. 60% chance or
01159            * always ok if no road allowed. */
01160           rcmd = DiagDirToRoadBits(target_dir);
01161           allow_house = (!IsRoadAllowedHere(t1, house_tile, target_dir) || Chance16(6, 10));
01162           break;
01163       }
01164     }
01165 
01166     if (allow_house) {
01167       /* Build a house, but not if there already is a house there. */
01168       if (!IsTileType(house_tile, MP_HOUSE)) {
01169         /* Level the land if possible */
01170         if (Chance16(1, 6)) LevelTownLand(house_tile);
01171 
01172         /* And build a house.
01173          * Set result to -1 if we managed to build it. */
01174         if (BuildTownHouse(t1, house_tile)) {
01175           _grow_town_result = GROWTH_SUCCEED;
01176         }
01177       }
01178       return;
01179     }
01180 
01181     _grow_town_result = GROWTH_SEARCH_STOPPED;
01182   }
01183 
01184   /* Return if a water tile */
01185   if (IsWaterTile(tile)) return;
01186 
01187   /* Make the roads look nicer */
01188   rcmd = CleanUpRoadBits(tile, rcmd);
01189   if (rcmd == ROAD_NONE) return;
01190 
01191   /* Only use the target direction for bridges to ensure they're connected.
01192    * The target_dir is as computed previously according to town layout, so
01193    * it will match it perfectly. */
01194   if (GrowTownWithBridge(t1, tile, target_dir)) return;
01195 
01196   GrowTownWithRoad(t1, tile, rcmd);
01197 }
01198 
01204 static int GrowTownAtRoad(Town *t, TileIndex tile)
01205 {
01206   /* Special case.
01207    * @see GrowTownInTile Check the else if
01208    */
01209   DiagDirection target_dir = DIAGDIR_END; // The direction in which we want to extend the town
01210 
01211   assert(tile < MapSize());
01212 
01213   /* Number of times to search.
01214    * Better roads, 2X2 and 3X3 grid grow quite fast so we give
01215    * them a little handicap. */
01216   switch (t->layout) {
01217     case TL_BETTER_ROADS:
01218       _grow_town_result = 10 + t->num_houses * 2 / 9;
01219       break;
01220 
01221     case TL_3X3_GRID:
01222     case TL_2X2_GRID:
01223       _grow_town_result = 10 + t->num_houses * 1 / 9;
01224       break;
01225 
01226     default:
01227       _grow_town_result = 10 + t->num_houses * 4 / 9;
01228       break;
01229   }
01230 
01231   do {
01232     RoadBits cur_rb = GetTownRoadBits(tile); // The RoadBits of the current tile
01233 
01234     /* Try to grow the town from this point */
01235     GrowTownInTile(&tile, cur_rb, target_dir, t);
01236 
01237     /* Exclude the source position from the bitmask
01238      * and return if no more road blocks available */
01239     cur_rb &= ~DiagDirToRoadBits(ReverseDiagDir(target_dir));
01240     if (cur_rb == ROAD_NONE)
01241       return _grow_town_result;
01242 
01243     /* Select a random bit from the blockmask, walk a step
01244      * and continue the search from there. */
01245     do target_dir = RandomDiagDir(); while (!(cur_rb & DiagDirToRoadBits(target_dir)));
01246     tile = TileAddByDiagDir(tile, target_dir);
01247 
01248     if (IsTileType(tile, MP_ROAD) && !IsRoadDepot(tile) && HasTileRoadType(tile, ROADTYPE_ROAD)) {
01249       /* Don't allow building over roads of other cities */
01250       if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN) && Town::GetByTile(tile) != t) {
01251         _grow_town_result = GROWTH_SUCCEED;
01252       } else if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_NONE) && _game_mode == GM_EDITOR) {
01253         /* If we are in the SE, and this road-piece has no town owner yet, it just found an
01254          * owner :) (happy happy happy road now) */
01255         SetRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN);
01256         SetTownIndex(tile, t->index);
01257       }
01258     }
01259 
01260     /* Max number of times is checked. */
01261   } while (--_grow_town_result >= 0);
01262 
01263   return (_grow_town_result == -2);
01264 }
01265 
01273 static RoadBits GenRandomRoadBits()
01274 {
01275   uint32 r = Random();
01276   uint a = GB(r, 0, 2);
01277   uint b = GB(r, 8, 2);
01278   if (a == b) b ^= 2;
01279   return (RoadBits)((ROAD_NW << a) + (ROAD_NW << b));
01280 }
01281 
01286 static bool GrowTown(Town *t)
01287 {
01288   static const TileIndexDiffC _town_coord_mod[] = {
01289     {-1,  0},
01290     { 1,  1},
01291     { 1, -1},
01292     {-1, -1},
01293     {-1,  0},
01294     { 0,  2},
01295     { 2,  0},
01296     { 0, -2},
01297     {-1, -1},
01298     {-2,  2},
01299     { 2,  2},
01300     { 2, -2},
01301     { 0,  0}
01302   };
01303 
01304   /* Current "company" is a town */
01305   CompanyID old_company = _current_company;
01306   _current_company = OWNER_TOWN;
01307 
01308   TileIndex tile = t->xy; // The tile we are working with ATM
01309 
01310   /* Find a road that we can base the construction on. */
01311   const TileIndexDiffC *ptr;
01312   for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
01313     if (GetTownRoadBits(tile) != ROAD_NONE) {
01314       int r = GrowTownAtRoad(t, tile);
01315       _current_company = old_company;
01316       return r != 0;
01317     }
01318     tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
01319   }
01320 
01321   /* No road available, try to build a random road block by
01322    * clearing some land and then building a road there. */
01323   if (_settings_game.economy.allow_town_roads || _generating_world) {
01324     tile = t->xy;
01325     for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
01326       /* Only work with plain land that not already has a house */
01327       if (!IsTileType(tile, MP_HOUSE) && GetTileSlope(tile, NULL) == SLOPE_FLAT) {
01328         if (DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded()) {
01329           DoCommand(tile, GenRandomRoadBits(), t->index, DC_EXEC | DC_AUTO, CMD_BUILD_ROAD);
01330           _current_company = old_company;
01331           return true;
01332         }
01333       }
01334       tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
01335     }
01336   }
01337 
01338   _current_company = old_company;
01339   return false;
01340 }
01341 
01342 void UpdateTownRadius(Town *t)
01343 {
01344   static const uint32 _town_squared_town_zone_radius_data[23][5] = {
01345     {  4,  0,  0,  0,  0}, // 0
01346     { 16,  0,  0,  0,  0},
01347     { 25,  0,  0,  0,  0},
01348     { 36,  0,  0,  0,  0},
01349     { 49,  0,  4,  0,  0},
01350     { 64,  0,  4,  0,  0}, // 20
01351     { 64,  0,  9,  0,  1},
01352     { 64,  0,  9,  0,  4},
01353     { 64,  0, 16,  0,  4},
01354     { 81,  0, 16,  0,  4},
01355     { 81,  0, 16,  0,  4}, // 40
01356     { 81,  0, 25,  0,  9},
01357     { 81, 36, 25,  0,  9},
01358     { 81, 36, 25, 16,  9},
01359     { 81, 49,  0, 25,  9},
01360     { 81, 64,  0, 25,  9}, // 60
01361     { 81, 64,  0, 36,  9},
01362     { 81, 64,  0, 36, 16},
01363     {100, 81,  0, 49, 16},
01364     {100, 81,  0, 49, 25},
01365     {121, 81,  0, 49, 25}, // 80
01366     {121, 81,  0, 49, 25},
01367     {121, 81,  0, 49, 36}, // 88
01368   };
01369 
01370   if (t->num_houses < 92) {
01371     memcpy(t->squared_town_zone_radius, _town_squared_town_zone_radius_data[t->num_houses / 4], sizeof(t->squared_town_zone_radius));
01372   } else {
01373     int mass = t->num_houses / 8;
01374     /* Actually we are proportional to sqrt() but that's right because we are covering an area.
01375      * The offsets are to make sure the radii do not decrease in size when going from the table
01376      * to the calculated value.*/
01377     t->squared_town_zone_radius[0] = mass * 15 - 40;
01378     t->squared_town_zone_radius[1] = mass * 9 - 15;
01379     t->squared_town_zone_radius[2] = 0;
01380     t->squared_town_zone_radius[3] = mass * 5 - 5;
01381     t->squared_town_zone_radius[4] = mass * 3 + 5;
01382   }
01383 }
01384 
01385 void UpdateTownMaxPass(Town *t)
01386 {
01387   t->max_pass = t->population >> 3;
01388   t->max_mail = t->population >> 4;
01389 }
01390 
01402 static void DoCreateTown(Town *t, TileIndex tile, uint32 townnameparts, TownSize size, bool city, TownLayout layout, bool manual)
01403 {
01404   t->xy = tile;
01405   t->num_houses = 0;
01406   t->time_until_rebuild = 10;
01407   UpdateTownRadius(t);
01408   t->flags = 0;
01409   t->population = 0;
01410   t->grow_counter = 0;
01411   t->growth_rate = 250;
01412   t->new_max_pass = 0;
01413   t->new_max_mail = 0;
01414   t->new_act_pass = 0;
01415   t->new_act_mail = 0;
01416   t->max_pass = 0;
01417   t->max_mail = 0;
01418   t->act_pass = 0;
01419   t->act_mail = 0;
01420 
01421   t->pct_pass_transported = 0;
01422   t->pct_mail_transported = 0;
01423   t->fund_buildings_months = 0;
01424   t->new_act_food = 0;
01425   t->new_act_water = 0;
01426   t->act_food = 0;
01427   t->act_water = 0;
01428 
01429   for (uint i = 0; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
01430 
01431   t->have_ratings = 0;
01432   t->exclusivity = INVALID_COMPANY;
01433   t->exclusive_counter = 0;
01434   t->statues = 0;
01435 
01436   extern int _nb_orig_names;
01437   if (_settings_game.game_creation.town_name < _nb_orig_names) {
01438     /* Original town name */
01439     t->townnamegrfid = 0;
01440     t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
01441   } else {
01442     /* Newgrf town name */
01443     t->townnamegrfid = GetGRFTownNameId(_settings_game.game_creation.town_name  - _nb_orig_names);
01444     t->townnametype  = GetGRFTownNameType(_settings_game.game_creation.town_name - _nb_orig_names);
01445   }
01446   t->townnameparts = townnameparts;
01447 
01448   t->UpdateVirtCoord();
01449   InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
01450 
01451   t->InitializeLayout(layout);
01452 
01453   t->larger_town = city;
01454 
01455   int x = (int)size * 16 + 3;
01456   if (size == TSZ_RANDOM) x = (Random() & 0xF) + 8;
01457   /* Don't create huge cities when founding town in-game */
01458   if (city && (!manual || _game_mode == GM_EDITOR)) x *= _settings_game.economy.initial_city_size;
01459 
01460   t->num_houses += x;
01461   UpdateTownRadius(t);
01462 
01463   int i = x * 4;
01464   do {
01465     GrowTown(t);
01466   } while (--i);
01467 
01468   t->num_houses -= x;
01469   UpdateTownRadius(t);
01470   UpdateTownMaxPass(t);
01471   UpdateAirportsNoise();
01472 }
01473 
01479 static CommandCost TownCanBePlacedHere(TileIndex tile)
01480 {
01481   /* Check if too close to the edge of map */
01482   if (DistanceFromEdge(tile) < 12) {
01483     return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP_SUB);
01484   }
01485 
01486   /* Check distance to all other towns. */
01487   if (IsCloseToTown(tile, 20)) {
01488     return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_TOWN);
01489   }
01490 
01491   /* Can only build on clear flat areas, possibly with trees. */
01492   if ((!IsTileType(tile, MP_CLEAR) && !IsTileType(tile, MP_TREES)) || GetTileSlope(tile, NULL) != SLOPE_FLAT) {
01493     return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
01494   }
01495 
01496   return CommandCost(EXPENSES_OTHER);
01497 }
01498 
01504 static bool IsUniqueTownName(const char *name)
01505 {
01506   const Town *t;
01507 
01508   FOR_ALL_TOWNS(t) {
01509     if (t->name != NULL && strcmp(t->name, name) == 0) return false;
01510   }
01511 
01512   return true;
01513 }
01514 
01527 CommandCost CmdFoundTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01528 {
01529   TownSize size = Extract<TownSize, 0, 2>(p1);
01530   bool city = HasBit(p1, 2);
01531   TownLayout layout = Extract<TownLayout, 3, 3>(p1);
01532   TownNameParams par(_settings_game.game_creation.town_name);
01533   bool random = HasBit(p1, 6);
01534   uint32 townnameparts = p2;
01535 
01536   if (size > TSZ_RANDOM) return CMD_ERROR;
01537   if (layout > TL_RANDOM) return CMD_ERROR;
01538 
01539   /* Some things are allowed only in the scenario editor */
01540   if (_game_mode != GM_EDITOR) {
01541     if (_settings_game.economy.found_town == TF_FORBIDDEN) return CMD_ERROR;
01542     if (size == TSZ_LARGE) return CMD_ERROR;
01543     if (random) return CMD_ERROR;
01544     if (_settings_game.economy.found_town != TF_CUSTOM_LAYOUT && layout != _settings_game.economy.town_layout) {
01545       return CMD_ERROR;
01546     }
01547   }
01548 
01549   if (StrEmpty(text)) {
01550     /* If supplied name is empty, townnameparts has to generate unique automatic name */
01551     if (!VerifyTownName(townnameparts, &par)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
01552   } else {
01553     /* If name is not empty, it has to be unique custom name */
01554     if (strlen(text) >= MAX_LENGTH_TOWN_NAME_BYTES) return CMD_ERROR;
01555     if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
01556   }
01557 
01558   /* Allocate town struct */
01559   if (!Town::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_TOWNS);
01560 
01561   if (!random) {
01562     CommandCost ret = TownCanBePlacedHere(tile);
01563     if (ret.Failed()) return ret;
01564   }
01565 
01566   static const byte price_mult[][TSZ_RANDOM + 1] = {{ 15, 25, 40, 25 }, { 20, 35, 55, 35 }};
01567   /* multidimensional arrays have to have defined length of non-first dimension */
01568   assert_compile(lengthof(price_mult[0]) == 4);
01569 
01570   CommandCost cost(EXPENSES_OTHER, _price[PR_BUILD_TOWN]);
01571   byte mult = price_mult[city][size];
01572 
01573   cost.MultiplyCost(mult);
01574 
01575   /* Create the town */
01576   if (flags & DC_EXEC) {
01577     if (cost.GetCost() > GetAvailableMoneyForCommand()) {
01578       _additional_cash_required = cost.GetCost();
01579       return CommandCost(EXPENSES_OTHER);
01580     }
01581 
01582     _generating_world = true;
01583     UpdateNearestTownForRoadTiles(true);
01584     Town *t;
01585     if (random) {
01586       t = CreateRandomTown(20, townnameparts, size, city, layout);
01587       if (t == NULL) {
01588         cost = CommandCost(STR_ERROR_NO_SPACE_FOR_TOWN);
01589       } else {
01590         _new_town_id = t->index;
01591       }
01592     } else {
01593       t = new Town(tile);
01594       DoCreateTown(t, tile, townnameparts, size, city, layout, true);
01595     }
01596     UpdateNearestTownForRoadTiles(false);
01597     _generating_world = false;
01598 
01599     if (t != NULL && !StrEmpty(text)) {
01600       t->name = strdup(text);
01601       t->UpdateVirtCoord();
01602     }
01603 
01604     if (_game_mode != GM_EDITOR) {
01605       /* 't' can't be NULL since 'random' is false outside scenedit */
01606       assert(!random);
01607       char company_name[MAX_LENGTH_COMPANY_NAME_BYTES];
01608       SetDParam(0, _current_company);
01609       GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
01610 
01611       char *cn = strdup(company_name);
01612       SetDParamStr(0, cn);
01613       SetDParam(1, t->index);
01614 
01615       AddNewsItem(STR_NEWS_NEW_TOWN, NS_INDUSTRY_OPEN, NR_TILE, tile, NR_NONE, UINT32_MAX, cn);
01616     }
01617   }
01618   return cost;
01619 }
01620 
01630 static TileIndex AlignTileToGrid(TileIndex tile, TownLayout layout)
01631 {
01632   switch (layout) {
01633     case TL_2X2_GRID: return TileXY(TileX(tile) - TileX(tile) % 3, TileY(tile) - TileY(tile) % 3);
01634     case TL_3X3_GRID: return TileXY(TileX(tile) & ~3, TileY(tile) & ~3);
01635     default:          return tile;
01636   }
01637 }
01638 
01648 static bool IsTileAlignedToGrid(TileIndex tile, TownLayout layout)
01649 {
01650   switch (layout) {
01651     case TL_2X2_GRID: return TileX(tile) % 3 == 0 && TileY(tile) % 3 == 0;
01652     case TL_3X3_GRID: return TileX(tile) % 4 == 0 && TileY(tile) % 4 == 0;
01653     default:          return true;
01654   }
01655 }
01656 
01660 struct SpotData {
01661   TileIndex tile; 
01662   uint max_dist;  
01663   TownLayout layout; 
01664 };
01665 
01682 static bool FindFurthestFromWater(TileIndex tile, void *user_data)
01683 {
01684   SpotData *sp = (SpotData*)user_data;
01685   uint dist = GetClosestWaterDistance(tile, true);
01686 
01687   if (IsTileType(tile, MP_CLEAR) &&
01688       GetTileSlope(tile, NULL) == SLOPE_FLAT &&
01689       IsTileAlignedToGrid(tile, sp->layout) &&
01690       dist > sp->max_dist) {
01691     sp->tile = tile;
01692     sp->max_dist = dist;
01693   }
01694 
01695   return false;
01696 }
01697 
01704 static bool FindNearestEmptyLand(TileIndex tile, void *user_data)
01705 {
01706   return IsTileType(tile, MP_CLEAR);
01707 }
01708 
01721 static TileIndex FindNearestGoodCoastalTownSpot(TileIndex tile, TownLayout layout)
01722 {
01723   SpotData sp = { INVALID_TILE, 0, layout };
01724 
01725   TileIndex coast = tile;
01726   if (CircularTileSearch(&coast, 40, FindNearestEmptyLand, NULL)) {
01727     CircularTileSearch(&coast, 10, FindFurthestFromWater, &sp);
01728     return sp.tile;
01729   }
01730 
01731   /* if we get here just give up */
01732   return INVALID_TILE;
01733 }
01734 
01735 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout)
01736 {
01737   if (!Town::CanAllocateItem()) return NULL;
01738 
01739   do {
01740     /* Generate a tile index not too close from the edge */
01741     TileIndex tile = AlignTileToGrid(RandomTile(), layout);
01742 
01743     /* if we tried to place the town on water, slide it over onto
01744      * the nearest likely-looking spot */
01745     if (IsTileType(tile, MP_WATER)) {
01746       tile = FindNearestGoodCoastalTownSpot(tile, layout);
01747       if (tile == INVALID_TILE) continue;
01748     }
01749 
01750     /* Make sure town can be placed here */
01751     if (TownCanBePlacedHere(tile).Failed()) continue;
01752 
01753     /* Allocate a town struct */
01754     Town *t = new Town(tile);
01755 
01756     DoCreateTown(t, tile, townnameparts, size, city, layout, false);
01757 
01758     /* if the population is still 0 at the point, then the
01759      * placement is so bad it couldn't grow at all */
01760     if (t->population > 0) return t;
01761     delete t;
01762   } while (--attempts != 0);
01763 
01764   return NULL;
01765 }
01766 
01767 static const byte _num_initial_towns[4] = {5, 11, 23, 46};  // very low, low, normal, high
01768 
01775 bool GenerateTowns(TownLayout layout)
01776 {
01777   uint num = 0;
01778   uint difficulty = _settings_game.difficulty.number_towns;
01779   uint n = (difficulty == (uint)CUSTOM_TOWN_NUMBER_DIFFICULTY) ? _settings_game.game_creation.custom_town_number : ScaleByMapSize(_num_initial_towns[difficulty] + (Random() & 7));
01780   uint32 townnameparts;
01781 
01782   SetGeneratingWorldProgress(GWP_TOWN, n);
01783 
01784   /* First attempt will be made at creating the suggested number of towns.
01785    * Note that this is really a suggested value, not a required one.
01786    * We would not like the system to lock up just because the user wanted 100 cities on a 64*64 map, would we? */
01787   do {
01788     bool city = (_settings_game.economy.larger_towns != 0 && Chance16(1, _settings_game.economy.larger_towns));
01789     IncreaseGeneratingWorldProgress(GWP_TOWN);
01790     /* Get a unique name for the town. */
01791     if (!GenerateTownName(&townnameparts)) continue;
01792     /* try 20 times to create a random-sized town for the first loop. */
01793     if (CreateRandomTown(20, townnameparts, TSZ_RANDOM, city, layout) != NULL) num++; // If creation was successful, raise a flag.
01794   } while (--n);
01795 
01796   if (num != 0) return true;
01797 
01798   /* If num is still zero at this point, it means that not a single town has been created.
01799    * So give it a last try, but now more aggressive */
01800   if (GenerateTownName(&townnameparts) &&
01801       CreateRandomTown(10000, townnameparts, TSZ_RANDOM, _settings_game.economy.larger_towns != 0, layout) != NULL) {
01802     return true;
01803   }
01804 
01805   /* If there are no towns at all and we are generating new game, bail out */
01806   if (Town::GetNumItems() == 0 && _game_mode != GM_EDITOR) {
01807     extern StringID _switch_mode_errorstr;
01808     _switch_mode_errorstr = STR_ERROR_COULD_NOT_CREATE_TOWN;
01809   }
01810 
01811   return false;  // we are still without a town? we failed, simply
01812 }
01813 
01814 
01820 HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
01821 {
01822   uint dist = DistanceSquare(tile, t->xy);
01823 
01824   if (t->fund_buildings_months && dist <= 25) return HZB_TOWN_CENTRE;
01825 
01826   HouseZonesBits smallest = HZB_TOWN_EDGE;
01827   for (HouseZonesBits i = HZB_BEGIN; i < HZB_END; i++) {
01828     if (dist < t->squared_town_zone_radius[i]) smallest = i;
01829   }
01830 
01831   return smallest;
01832 }
01833 
01844 static inline void ClearMakeHouseTile(TileIndex tile, Town *t, byte counter, byte stage, HouseID type, byte random_bits)
01845 {
01846   CommandCost cc = DoCommand(tile, 0, 0, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR);
01847 
01848   assert(cc.Succeeded());
01849 
01850   IncreaseBuildingCount(t, type);
01851   MakeHouseTile(tile, t->index, counter, stage, type, random_bits);
01852   if (HouseSpec::Get(type)->building_flags & BUILDING_IS_ANIMATED) AddAnimatedTile(tile);
01853 
01854   MarkTileDirtyByTile(tile);
01855 }
01856 
01857 
01868 static void MakeTownHouse(TileIndex t, Town *town, byte counter, byte stage, HouseID type, byte random_bits)
01869 {
01870   BuildingFlags size = HouseSpec::Get(type)->building_flags;
01871 
01872   ClearMakeHouseTile(t, town, counter, stage, type, random_bits);
01873   if (size & BUILDING_2_TILES_Y)   ClearMakeHouseTile(t + TileDiffXY(0, 1), town, counter, stage, ++type, random_bits);
01874   if (size & BUILDING_2_TILES_X)   ClearMakeHouseTile(t + TileDiffXY(1, 0), town, counter, stage, ++type, random_bits);
01875   if (size & BUILDING_HAS_4_TILES) ClearMakeHouseTile(t + TileDiffXY(1, 1), town, counter, stage, ++type, random_bits);
01876 }
01877 
01878 
01887 static inline bool CanBuildHouseHere(TileIndex tile, TownID town, bool noslope)
01888 {
01889   /* cannot build on these slopes... */
01890   Slope slope = GetTileSlope(tile, NULL);
01891   if ((noslope && slope != SLOPE_FLAT) || IsSteepSlope(slope)) return false;
01892 
01893   /* building under a bridge? */
01894   if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return false;
01895 
01896   /* do not try to build over house owned by another town */
01897   if (IsTileType(tile, MP_HOUSE) && GetTownIndex(tile) != town) return false;
01898 
01899   /* can we clear the land? */
01900   return DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded();
01901 }
01902 
01903 
01913 static inline bool CheckBuildHouseSameZ(TileIndex tile, TownID town, uint z, bool noslope)
01914 {
01915   if (!CanBuildHouseHere(tile, town, noslope)) return false;
01916 
01917   /* if building on slopes is allowed, there will be flattening foundation (to tile max z) */
01918   if (GetTileMaxZ(tile) != z) return false;
01919 
01920   return true;
01921 }
01922 
01923 
01933 static bool CheckFree2x2Area(TileIndex tile, TownID town, uint z, bool noslope)
01934 {
01935   /* we need to check this tile too because we can be at different tile now */
01936   if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
01937 
01938   for (DiagDirection d = DIAGDIR_SE; d < DIAGDIR_END; d++) {
01939     tile += TileOffsByDiagDir(d);
01940     if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
01941   }
01942 
01943   return true;
01944 }
01945 
01946 
01954 static inline bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile)
01955 {
01956   /* Allow towns everywhere when we don't build roads */
01957   if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
01958 
01959   TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
01960 
01961   switch (t->layout) {
01962     case TL_2X2_GRID:
01963       if ((grid_pos.x % 3) == 0 || (grid_pos.y % 3) == 0) return false;
01964       break;
01965 
01966     case TL_3X3_GRID:
01967       if ((grid_pos.x % 4) == 0 || (grid_pos.y % 4) == 0) return false;
01968       break;
01969 
01970     default:
01971       break;
01972   }
01973 
01974   return true;
01975 }
01976 
01977 
01985 static inline bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile)
01986 {
01987   /* Allow towns everywhere when we don't build roads */
01988   if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
01989 
01990   /* MapSize() is sure dividable by both MapSizeX() and MapSizeY(),
01991    * so to do only one memory access, use MapSize() */
01992   uint dx = MapSize() + TileX(t->xy) - TileX(tile);
01993   uint dy = MapSize() + TileY(t->xy) - TileY(tile);
01994 
01995   switch (t->layout) {
01996     case TL_2X2_GRID:
01997       if ((dx % 3) != 0 || (dy % 3) != 0) return false;
01998       break;
01999 
02000     case TL_3X3_GRID:
02001       if ((dx % 4) < 2 || (dy % 4) < 2) return false;
02002       break;
02003 
02004     default:
02005       break;
02006   }
02007 
02008   return true;
02009 }
02010 
02011 
02021 static bool CheckTownBuild2House(TileIndex *tile, Town *t, uint maxz, bool noslope, DiagDirection second)
02022 {
02023   /* 'tile' is already checked in BuildTownHouse() - CanBuildHouseHere() and slope test */
02024 
02025   TileIndex tile2 = *tile + TileOffsByDiagDir(second);
02026   if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) return true;
02027 
02028   tile2 = *tile + TileOffsByDiagDir(ReverseDiagDir(second));
02029   if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) {
02030     *tile = tile2;
02031     return true;
02032   }
02033 
02034   return false;
02035 }
02036 
02037 
02046 static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, uint maxz, bool noslope)
02047 {
02048   TileIndex tile2 = *tile;
02049 
02050   for (DiagDirection d = DIAGDIR_SE;;d++) { // 'd' goes through DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_END
02051     if (TownLayoutAllows2x2HouseHere(t, tile2) && CheckFree2x2Area(tile2, t->index, maxz, noslope)) {
02052       *tile = tile2;
02053       return true;
02054     }
02055     if (d == DIAGDIR_END) break;
02056     tile2 += TileOffsByDiagDir(ReverseDiagDir(d)); // go clockwise
02057   }
02058 
02059   return false;
02060 }
02061 
02062 
02069 static bool BuildTownHouse(Town *t, TileIndex tile)
02070 {
02071   /* forbidden building here by town layout */
02072   if (!TownLayoutAllowsHouseHere(t, tile)) return false;
02073 
02074   /* no house allowed at all, bail out */
02075   if (!CanBuildHouseHere(tile, t->index, false)) return false;
02076 
02077   uint z;
02078   Slope slope = GetTileSlope(tile, &z);
02079 
02080   /* Get the town zone type of the current tile, as well as the climate.
02081    * This will allow to easily compare with the specs of the new house to build */
02082   HouseZonesBits rad = GetTownRadiusGroup(t, tile);
02083 
02084   /* Above snow? */
02085   int land = _settings_game.game_creation.landscape;
02086   if (land == LT_ARCTIC && z >= _settings_game.game_creation.snow_line) land = -1;
02087 
02088   uint bitmask = (1 << rad) + (1 << (land + 12));
02089 
02090   /* bits 0-4 are used
02091    * bits 11-15 are used
02092    * bits 5-10 are not used. */
02093   HouseID houses[HOUSE_MAX];
02094   uint num = 0;
02095   uint probs[HOUSE_MAX];
02096   uint probability_max = 0;
02097 
02098   /* Generate a list of all possible houses that can be built. */
02099   for (uint i = 0; i < HOUSE_MAX; i++) {
02100     const HouseSpec *hs = HouseSpec::Get(i);
02101 
02102     /* Verify that the candidate house spec matches the current tile status */
02103     if ((~hs->building_availability & bitmask) != 0 || !hs->enabled || hs->override != INVALID_HOUSE_ID) continue;
02104 
02105     /* Don't let these counters overflow. Global counters are 32bit, there will never be that many houses. */
02106     if (hs->class_id != HOUSE_NO_CLASS) {
02107       /* id_count is always <= class_count, so it doesn't need to be checked */
02108       if (t->building_counts.class_count[hs->class_id] == UINT16_MAX) continue;
02109     } else {
02110       /* If the house has no class, check id_count instead */
02111       if (t->building_counts.id_count[i] == UINT16_MAX) continue;
02112     }
02113 
02114     /* Without NewHouses, all houses have probability '1' */
02115     uint cur_prob = (_loaded_newgrf_features.has_newhouses ? hs->probability : 1);
02116     probability_max += cur_prob;
02117     probs[num] = cur_prob;
02118     houses[num++] = (HouseID)i;
02119   }
02120 
02121   uint maxz = GetTileMaxZ(tile);
02122 
02123   while (probability_max > 0) {
02124     uint r = RandomRange(probability_max);
02125     uint i;
02126     for (i = 0; i < num; i++) {
02127       if (probs[i] > r) break;
02128       r -= probs[i];
02129     }
02130 
02131     HouseID house = houses[i];
02132     probability_max -= probs[i];
02133 
02134     /* remove tested house from the set */
02135     num--;
02136     houses[i] = houses[num];
02137     probs[i] = probs[num];
02138 
02139     const HouseSpec *hs = HouseSpec::Get(house);
02140 
02141     if (_loaded_newgrf_features.has_newhouses && !_generating_world &&
02142         _game_mode != GM_EDITOR && (hs->extra_flags & BUILDING_IS_HISTORICAL) != 0) {
02143       continue;
02144     }
02145 
02146     if (_cur_year < hs->min_year || _cur_year > hs->max_year) continue;
02147 
02148     /* Special houses that there can be only one of. */
02149     uint oneof = 0;
02150 
02151     if (hs->building_flags & BUILDING_IS_CHURCH) {
02152       SetBit(oneof, TOWN_HAS_CHURCH);
02153     } else if (hs->building_flags & BUILDING_IS_STADIUM) {
02154       SetBit(oneof, TOWN_HAS_STADIUM);
02155     }
02156 
02157     if (t->flags & oneof) continue;
02158 
02159     /* Make sure there is no slope? */
02160     bool noslope = (hs->building_flags & TILE_NOT_SLOPED) != 0;
02161     if (noslope && slope != SLOPE_FLAT) continue;
02162 
02163     if (hs->building_flags & TILE_SIZE_2x2) {
02164       if (!CheckTownBuild2x2House(&tile, t, maxz, noslope)) continue;
02165     } else if (hs->building_flags & TILE_SIZE_2x1) {
02166       if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SW)) continue;
02167     } else if (hs->building_flags & TILE_SIZE_1x2) {
02168       if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SE)) continue;
02169     } else {
02170       /* 1x1 house checks are already done */
02171     }
02172 
02173     if (HasBit(hs->callback_mask, CBM_HOUSE_ALLOW_CONSTRUCTION)) {
02174       uint16 callback_res = GetHouseCallback(CBID_HOUSE_ALLOW_CONSTRUCTION, 0, 0, house, t, tile, true);
02175       if (callback_res != CALLBACK_FAILED && GB(callback_res, 0, 8) == 0) continue;
02176     }
02177 
02178     /* build the house */
02179     t->num_houses++;
02180 
02181     /* Special houses that there can be only one of. */
02182     t->flags |= oneof;
02183 
02184     byte construction_counter = 0;
02185     byte construction_stage = 0;
02186 
02187     if (_generating_world || _game_mode == GM_EDITOR) {
02188       uint32 r = Random();
02189 
02190       construction_stage = TOWN_HOUSE_COMPLETED;
02191       if (Chance16(1, 7)) construction_stage = GB(r, 0, 2);
02192 
02193       if (construction_stage == TOWN_HOUSE_COMPLETED) {
02194         ChangePopulation(t, hs->population);
02195       } else {
02196         construction_counter = GB(r, 2, 2);
02197       }
02198     }
02199 
02200     MakeTownHouse(tile, t, construction_counter, construction_stage, house, Random());
02201 
02202     return true;
02203   }
02204 
02205   return false;
02206 }
02207 
02214 static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
02215 {
02216   assert(IsTileType(tile, MP_HOUSE));
02217   DecreaseBuildingCount(t, house);
02218   DoClearSquare(tile);
02219   DeleteAnimatedTile(tile);
02220 }
02221 
02229 TileIndexDiff GetHouseNorthPart(HouseID &house)
02230 {
02231   if (house >= 3) { // house id 0,1,2 MUST be single tile houses, or this code breaks.
02232     if (HouseSpec::Get(house - 1)->building_flags & TILE_SIZE_2x1) {
02233       house--;
02234       return TileDiffXY(-1, 0);
02235     } else if (HouseSpec::Get(house - 1)->building_flags & BUILDING_2_TILES_Y) {
02236       house--;
02237       return TileDiffXY(0, -1);
02238     } else if (HouseSpec::Get(house - 2)->building_flags & BUILDING_HAS_4_TILES) {
02239       house -= 2;
02240       return TileDiffXY(-1, 0);
02241     } else if (HouseSpec::Get(house - 3)->building_flags & BUILDING_HAS_4_TILES) {
02242       house -= 3;
02243       return TileDiffXY(-1, -1);
02244     }
02245   }
02246   return 0;
02247 }
02248 
02249 void ClearTownHouse(Town *t, TileIndex tile)
02250 {
02251   assert(IsTileType(tile, MP_HOUSE));
02252 
02253   HouseID house = GetHouseType(tile);
02254 
02255   /* need to align the tile to point to the upper left corner of the house */
02256   tile += GetHouseNorthPart(house); // modifies house to the ID of the north tile
02257 
02258   const HouseSpec *hs = HouseSpec::Get(house);
02259 
02260   /* Remove population from the town if the house is finished. */
02261   if (IsHouseCompleted(tile)) {
02262     ChangePopulation(t, -hs->population);
02263   }
02264 
02265   t->num_houses--;
02266 
02267   /* Clear flags for houses that only may exist once/town. */
02268   if (hs->building_flags & BUILDING_IS_CHURCH) {
02269     ClrBit(t->flags, TOWN_HAS_CHURCH);
02270   } else if (hs->building_flags & BUILDING_IS_STADIUM) {
02271     ClrBit(t->flags, TOWN_HAS_STADIUM);
02272   }
02273 
02274   /* Do the actual clearing of tiles */
02275   uint eflags = hs->building_flags;
02276   DoClearTownHouseHelper(tile, t, house);
02277   if (eflags & BUILDING_2_TILES_Y)   DoClearTownHouseHelper(tile + TileDiffXY(0, 1), t, ++house);
02278   if (eflags & BUILDING_2_TILES_X)   DoClearTownHouseHelper(tile + TileDiffXY(1, 0), t, ++house);
02279   if (eflags & BUILDING_HAS_4_TILES) DoClearTownHouseHelper(tile + TileDiffXY(1, 1), t, ++house);
02280 }
02281 
02290 CommandCost CmdRenameTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02291 {
02292   Town *t = Town::GetIfValid(p1);
02293   if (t == NULL) return CMD_ERROR;
02294 
02295   bool reset = StrEmpty(text);
02296 
02297   if (!reset) {
02298     if (strlen(text) >= MAX_LENGTH_TOWN_NAME_BYTES) return CMD_ERROR;
02299     if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
02300   }
02301 
02302   if (flags & DC_EXEC) {
02303     free(t->name);
02304     t->name = reset ? NULL : strdup(text);
02305 
02306     t->UpdateVirtCoord();
02307     InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
02308     UpdateAllStationVirtCoords();
02309   }
02310   return CommandCost();
02311 }
02312 
02314 void ExpandTown(Town *t)
02315 {
02316   /* Warn the users if towns are not allowed to build roads,
02317    * but do this only onces per openttd run. */
02318   static bool warned_no_roads = false;
02319   if (!_settings_game.economy.allow_town_roads && !warned_no_roads) {
02320     ShowErrorMessage(STR_ERROR_TOWN_EXPAND_WARN_NO_ROADS, INVALID_STRING_ID, 0, 0);
02321     warned_no_roads = true;
02322   }
02323 
02324   /* The more houses, the faster we grow */
02325   uint amount = RandomRange(ClampToU16(t->num_houses / 10)) + 3;
02326   t->num_houses += amount;
02327   UpdateTownRadius(t);
02328 
02329   uint n = amount * 10;
02330   do GrowTown(t); while (--n);
02331 
02332   t->num_houses -= amount;
02333   UpdateTownRadius(t);
02334 
02335   UpdateTownMaxPass(t);
02336 }
02337 
02341 const byte _town_action_costs[TACT_COUNT] = {
02342   2, 4, 9, 35, 48, 53, 117, 175
02343 };
02344 
02345 static CommandCost TownActionAdvertiseSmall(Town *t, DoCommandFlag flags)
02346 {
02347   if (flags & DC_EXEC) {
02348     ModifyStationRatingAround(t->xy, _current_company, 0x40, 10);
02349   }
02350   return CommandCost();
02351 }
02352 
02353 static CommandCost TownActionAdvertiseMedium(Town *t, DoCommandFlag flags)
02354 {
02355   if (flags & DC_EXEC) {
02356     ModifyStationRatingAround(t->xy, _current_company, 0x70, 15);
02357   }
02358   return CommandCost();
02359 }
02360 
02361 static CommandCost TownActionAdvertiseLarge(Town *t, DoCommandFlag flags)
02362 {
02363   if (flags & DC_EXEC) {
02364     ModifyStationRatingAround(t->xy, _current_company, 0xA0, 20);
02365   }
02366   return CommandCost();
02367 }
02368 
02369 static CommandCost TownActionRoadRebuild(Town *t, DoCommandFlag flags)
02370 {
02371   if (flags & DC_EXEC) {
02372     t->road_build_months = 6;
02373 
02374     char company_name[MAX_LENGTH_COMPANY_NAME_BYTES];
02375     SetDParam(0, _current_company);
02376     GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
02377 
02378     char *cn = strdup(company_name);
02379     SetDParam(0, t->index);
02380     SetDParamStr(1, cn);
02381 
02382     AddNewsItem(STR_NEWS_ROAD_REBUILDING, NS_GENERAL, NR_TOWN, t->index, NR_NONE, UINT32_MAX, cn);
02383   }
02384   return CommandCost();
02385 }
02386 
02393 static bool SearchTileForStatue(TileIndex tile, void *user_data)
02394 {
02395   /* Statues can be build on slopes, just like houses. Only the steep slopes is a no go. */
02396   if (IsSteepSlope(GetTileSlope(tile, NULL))) return false;
02397   /* Don't build statues under bridges. */
02398   if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return false;
02399 
02400   if (!IsTileType(tile, MP_HOUSE) &&
02401       !IsTileType(tile, MP_CLEAR) &&
02402       !IsTileType(tile, MP_TREES)) {
02403     return false;
02404   }
02405 
02406   CompanyID old = _current_company;
02407   _current_company = OWNER_NONE;
02408   CommandCost r = DoCommand(tile, 0, 0, DC_NONE, CMD_LANDSCAPE_CLEAR);
02409   _current_company = old;
02410 
02411   if (r.Failed()) return false;
02412 
02413   return true;
02414 }
02415 
02423 static CommandCost TownActionBuildStatue(Town *t, DoCommandFlag flags)
02424 {
02425   TileIndex tile = t->xy;
02426   if (CircularTileSearch(&tile, 9, SearchTileForStatue, NULL)) {
02427     if (flags & DC_EXEC) {
02428       CompanyID old = _current_company;
02429       _current_company = OWNER_NONE;
02430       DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
02431       _current_company = old;
02432       MakeStatue(tile, _current_company, t->index);
02433       SetBit(t->statues, _current_company); // Once found and built, "inform" the Town.
02434       MarkTileDirtyByTile(tile);
02435     }
02436     return CommandCost();
02437   }
02438   return_cmd_error(STR_ERROR_STATUE_NO_SUITABLE_PLACE);
02439 }
02440 
02441 static CommandCost TownActionFundBuildings(Town *t, DoCommandFlag flags)
02442 {
02443   if (flags & DC_EXEC) {
02444     /* Build next tick */
02445     t->grow_counter = 1;
02446     /* If we were not already growing */
02447     SetBit(t->flags, TOWN_IS_FUNDED);
02448     /* And grow for 3 months */
02449     t->fund_buildings_months = 3;
02450   }
02451   return CommandCost();
02452 }
02453 
02454 static CommandCost TownActionBuyRights(Town *t, DoCommandFlag flags)
02455 {
02456   /* Check if it's allowed to by the rights */
02457   if (!_settings_game.economy.exclusive_rights) return CMD_ERROR;
02458 
02459   if (flags & DC_EXEC) {
02460     t->exclusive_counter = 12;
02461     t->exclusivity = _current_company;
02462 
02463     ModifyStationRatingAround(t->xy, _current_company, 130, 17);
02464   }
02465   return CommandCost();
02466 }
02467 
02468 static CommandCost TownActionBribe(Town *t, DoCommandFlag flags)
02469 {
02470   if (flags & DC_EXEC) {
02471     if (Chance16(1, 14)) {
02472       /* set as unwanted for 6 months */
02473       t->unwanted[_current_company] = 6;
02474 
02475       /* set all close by station ratings to 0 */
02476       Station *st;
02477       FOR_ALL_STATIONS(st) {
02478         if (st->town == t && st->owner == _current_company) {
02479           for (CargoID i = 0; i < NUM_CARGO; i++) st->goods[i].rating = 0;
02480         }
02481       }
02482 
02483       /* only show errormessage to the executing player. All errors are handled command.c
02484        * but this is special, because it can only 'fail' on a DC_EXEC */
02485       if (IsLocalCompany()) ShowErrorMessage(STR_ERROR_BRIBE_FAILED, STR_ERROR_BRIBE_FAILED_2, 0, 0);
02486 
02487       /* decrease by a lot!
02488        * ChangeTownRating is only for stuff in demolishing. Bribe failure should
02489        * be independent of any cheat settings
02490        */
02491       if (t->ratings[_current_company] > RATING_BRIBE_DOWN_TO) {
02492         t->ratings[_current_company] = RATING_BRIBE_DOWN_TO;
02493         SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
02494       }
02495     } else {
02496       ChangeTownRating(t, RATING_BRIBE_UP_STEP, RATING_BRIBE_MAXIMUM, DC_EXEC);
02497     }
02498   }
02499   return CommandCost();
02500 }
02501 
02502 typedef CommandCost TownActionProc(Town *t, DoCommandFlag flags);
02503 static TownActionProc * const _town_action_proc[] = {
02504   TownActionAdvertiseSmall,
02505   TownActionAdvertiseMedium,
02506   TownActionAdvertiseLarge,
02507   TownActionRoadRebuild,
02508   TownActionBuildStatue,
02509   TownActionFundBuildings,
02510   TownActionBuyRights,
02511   TownActionBribe
02512 };
02513 
02520 uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t)
02521 {
02522   int num = 0;
02523   TownActions buttons = TACT_NONE;
02524 
02525   /* Spectators and unwanted have no options */
02526   if (cid != COMPANY_SPECTATOR && !(_settings_game.economy.bribe && t->unwanted[cid])) {
02527 
02528     /* Things worth more than this are not shown */
02529     Money avail = Company::Get(cid)->money + _price[PR_STATION_VALUE] * 200;
02530 
02531     /* Check the action bits for validity and
02532      * if they are valid add them */
02533     for (uint i = 0; i != lengthof(_town_action_costs); i++) {
02534       const TownActions cur = (TownActions)(1 << i);
02535 
02536       /* Is the company not able to bribe ? */
02537       if (cur == TACT_BRIBE && (!_settings_game.economy.bribe || t->ratings[cid] >= RATING_BRIBE_MAXIMUM))
02538         continue;
02539 
02540       /* Is the company not able to buy exclusive rights ? */
02541       if (cur == TACT_BUY_RIGHTS && !_settings_game.economy.exclusive_rights)
02542         continue;
02543 
02544       /* Is the company not able to build a statue ? */
02545       if (cur == TACT_BUILD_STATUE && HasBit(t->statues, cid))
02546         continue;
02547 
02548       if (avail >= _town_action_costs[i] * _price[PR_TOWN_ACTION] >> 8) {
02549         buttons |= cur;
02550         num++;
02551       }
02552     }
02553   }
02554 
02555   if (nump != NULL) *nump = num;
02556   return buttons;
02557 }
02558 
02569 CommandCost CmdDoTownAction(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02570 {
02571   Town *t = Town::GetIfValid(p1);
02572   if (t == NULL || p2 >= lengthof(_town_action_proc)) return CMD_ERROR;
02573 
02574   if (!HasBit(GetMaskOfTownActions(NULL, _current_company, t), p2)) return CMD_ERROR;
02575 
02576   CommandCost cost(EXPENSES_OTHER, _price[PR_TOWN_ACTION] * _town_action_costs[p2] >> 8);
02577 
02578   CommandCost ret = _town_action_proc[p2](t, flags);
02579   if (ret.Failed()) return ret;
02580 
02581   if (flags & DC_EXEC) {
02582     SetWindowDirty(WC_TOWN_AUTHORITY, p1);
02583   }
02584 
02585   return cost;
02586 }
02587 
02588 static void UpdateTownGrowRate(Town *t)
02589 {
02590   /* Increase company ratings if they're low */
02591   const Company *c;
02592   FOR_ALL_COMPANIES(c) {
02593     if (t->ratings[c->index] < RATING_GROWTH_MAXIMUM) {
02594       t->ratings[c->index] = min((int)RATING_GROWTH_MAXIMUM, t->ratings[c->index] + RATING_GROWTH_UP_STEP);
02595     }
02596   }
02597 
02598   int n = 0;
02599 
02600   const Station *st;
02601   FOR_ALL_STATIONS(st) {
02602     if (DistanceSquare(st->xy, t->xy) <= t->squared_town_zone_radius[0]) {
02603       if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
02604         n++;
02605         if (Company::IsValidID(st->owner)) {
02606           int new_rating = t->ratings[st->owner] + RATING_STATION_UP_STEP;
02607           t->ratings[st->owner] = min(new_rating, INT16_MAX); // do not let it overflow
02608         }
02609       } else {
02610         if (Company::IsValidID(st->owner)) {
02611           int new_rating = t->ratings[st->owner] + RATING_STATION_DOWN_STEP;
02612           t->ratings[st->owner] = max(new_rating, INT16_MIN);
02613         }
02614       }
02615     }
02616   }
02617 
02618   /* clamp all ratings to valid values */
02619   for (uint i = 0; i < MAX_COMPANIES; i++) {
02620     t->ratings[i] = Clamp(t->ratings[i], RATING_MINIMUM, RATING_MAXIMUM);
02621   }
02622 
02623   SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
02624 
02625   ClrBit(t->flags, TOWN_IS_FUNDED);
02626   if (_settings_game.economy.town_growth_rate == 0 && t->fund_buildings_months == 0) return;
02627 
02630   static const uint16 _grow_count_values[2][6] = {
02631     { 120, 120, 120, 100,  80,  60 }, // Fund new buildings has been activated
02632     { 320, 420, 300, 220, 160, 100 }  // Normal values
02633   };
02634 
02635   uint16 m;
02636 
02637   if (t->fund_buildings_months != 0) {
02638     m = _grow_count_values[0][min(n, 5)];
02639     t->fund_buildings_months--;
02640   } else {
02641     m = _grow_count_values[1][min(n, 5)];
02642     if (n == 0 && !Chance16(1, 12)) return;
02643   }
02644 
02645   if (_settings_game.game_creation.landscape == LT_ARCTIC) {
02646     if (TilePixelHeight(t->xy) >= GetSnowLine() && t->act_food == 0 && t->population > 90)
02647       return;
02648   } else if (_settings_game.game_creation.landscape == LT_TROPIC) {
02649     if (GetTropicZone(t->xy) == TROPICZONE_DESERT && (t->act_food == 0 || t->act_water == 0) && t->population > 60)
02650       return;
02651   }
02652 
02653   /* Use the normal growth rate values if new buildings have been funded in
02654    * this town and the growth rate is set to none. */
02655   uint growth_multiplier = _settings_game.economy.town_growth_rate != 0 ? _settings_game.economy.town_growth_rate - 1 : 1;
02656 
02657   m >>= growth_multiplier;
02658   if (t->larger_town) m /= 2;
02659 
02660   t->growth_rate = m / (t->num_houses / 50 + 1);
02661   if (m <= t->grow_counter)
02662     t->grow_counter = m;
02663 
02664   SetBit(t->flags, TOWN_IS_FUNDED);
02665 }
02666 
02667 static void UpdateTownAmounts(Town *t)
02668 {
02669   /* Using +1 here to prevent overflow and division by zero */
02670   t->pct_pass_transported = t->new_act_pass * 256 / (t->new_max_pass + 1);
02671 
02672   t->max_pass = t->new_max_pass; t->new_max_pass = 0;
02673   t->act_pass = t->new_act_pass; t->new_act_pass = 0;
02674   t->act_food = t->new_act_food; t->new_act_food = 0;
02675   t->act_water = t->new_act_water; t->new_act_water = 0;
02676 
02677   /* Using +1 here to prevent overflow and division by zero */
02678   t->pct_mail_transported = t->new_act_mail * 256 / (t->new_max_mail + 1);
02679   t->max_mail = t->new_max_mail; t->new_max_mail = 0;
02680   t->act_mail = t->new_act_mail; t->new_act_mail = 0;
02681 
02682   SetWindowDirty(WC_TOWN_VIEW, t->index);
02683 }
02684 
02685 static void UpdateTownUnwanted(Town *t)
02686 {
02687   const Company *c;
02688 
02689   FOR_ALL_COMPANIES(c) {
02690     if (t->unwanted[c->index] > 0) t->unwanted[c->index]--;
02691   }
02692 }
02693 
02699 bool CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags)
02700 {
02701   if (!Company::IsValidID(_current_company) || (flags & DC_NO_TEST_TOWN_RATING)) return true;
02702 
02703   Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
02704   if (t == NULL) return true;
02705 
02706   if (t->ratings[_current_company] > RATING_VERYPOOR) return true;
02707 
02708   _error_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS;
02709   SetDParam(0, t->index);
02710 
02711   return false;
02712 }
02713 
02714 
02715 Town *CalcClosestTownFromTile(TileIndex tile, uint threshold)
02716 {
02717   Town *t;
02718   uint best = threshold;
02719   Town *best_town = NULL;
02720 
02721   FOR_ALL_TOWNS(t) {
02722     uint dist = DistanceManhattan(tile, t->xy);
02723     if (dist < best) {
02724       best = dist;
02725       best_town = t;
02726     }
02727   }
02728 
02729   return best_town;
02730 }
02731 
02732 
02733 Town *ClosestTownFromTile(TileIndex tile, uint threshold)
02734 {
02735   switch (GetTileType(tile)) {
02736     case MP_ROAD:
02737       if (IsRoadDepot(tile)) return CalcClosestTownFromTile(tile, threshold);
02738 
02739       if (!HasTownOwnedRoad(tile)) {
02740         TownID tid = GetTownIndex(tile);
02741 
02742         if (tid == (TownID)INVALID_TOWN) {
02743           /* in the case we are generating "many random towns", this value may be INVALID_TOWN */
02744           if (_generating_world) return CalcClosestTownFromTile(tile, threshold);
02745           assert(Town::GetNumItems() == 0);
02746           return NULL;
02747         }
02748 
02749         assert(Town::IsValidID(tid));
02750         Town *town = Town::Get(tid);
02751 
02752         if (DistanceManhattan(tile, town->xy) >= threshold) town = NULL;
02753 
02754         return town;
02755       }
02756       /* FALL THROUGH */
02757 
02758     case MP_HOUSE:
02759       return Town::GetByTile(tile);
02760 
02761     default:
02762       return CalcClosestTownFromTile(tile, threshold);
02763   }
02764 }
02765 
02766 static bool _town_rating_test = false;
02767 static SmallMap<const Town *, int, 4> _town_test_ratings;
02768 
02769 void SetTownRatingTestMode(bool mode)
02770 {
02771   static int ref_count = 0;
02772   if (mode) {
02773     if (ref_count == 0) {
02774       _town_test_ratings.Clear();
02775     }
02776     ref_count++;
02777   } else {
02778     assert(ref_count > 0);
02779     ref_count--;
02780   }
02781   _town_rating_test = !(ref_count == 0);
02782 }
02783 
02784 static int GetRating(const Town *t)
02785 {
02786   if (_town_rating_test) {
02787     SmallMap<const Town *, int>::iterator it = _town_test_ratings.Find(t);
02788     if (it != _town_test_ratings.End()) {
02789       return it->second;
02790     }
02791   }
02792   return t->ratings[_current_company];
02793 }
02794 
02802 void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
02803 {
02804   /* if magic_bulldozer cheat is active, town doesn't penaltize for removing stuff */
02805   if (t == NULL || (flags & DC_NO_MODIFY_TOWN_RATING) ||
02806       !Company::IsValidID(_current_company) ||
02807       (_cheats.magic_bulldozer.value && add < 0)) {
02808     return;
02809   }
02810 
02811   int rating = GetRating(t);
02812   if (add < 0) {
02813     if (rating > max) {
02814       rating += add;
02815       if (rating < max) rating = max;
02816     }
02817   } else {
02818     if (rating < max) {
02819       rating += add;
02820       if (rating > max) rating = max;
02821     }
02822   }
02823   if (_town_rating_test) {
02824     _town_test_ratings[t] = rating;
02825   } else {
02826     SetBit(t->have_ratings, _current_company);
02827     t->ratings[_current_company] = rating;
02828     SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
02829   }
02830 }
02831 
02832 bool CheckforTownRating(DoCommandFlag flags, Town *t, TownRatingCheckType type)
02833 {
02834   /* if magic_bulldozer cheat is active, town doesn't restrict your destructive actions */
02835   if (t == NULL || !Company::IsValidID(_current_company) ||
02836       _cheats.magic_bulldozer.value || (flags & DC_NO_TEST_TOWN_RATING)) {
02837     return true;
02838   }
02839 
02840   /* minimum rating needed to be allowed to remove stuff */
02841   static const int needed_rating[][TOWN_RATING_CHECK_TYPE_COUNT] = {
02842     /*                  ROAD_REMOVE,                    TUNNELBRIDGE_REMOVE */
02843     { RATING_ROAD_NEEDED_PERMISSIVE, RATING_TUNNEL_BRIDGE_NEEDED_PERMISSIVE}, // Permissive
02844     {    RATING_ROAD_NEEDED_NEUTRAL,    RATING_TUNNEL_BRIDGE_NEEDED_NEUTRAL}, // Neutral
02845     {    RATING_ROAD_NEEDED_HOSTILE,    RATING_TUNNEL_BRIDGE_NEEDED_HOSTILE}, // Hostile
02846   };
02847 
02848   /* check if you're allowed to remove the road/bridge/tunnel
02849    * owned by a town no removal if rating is lower than ... depends now on
02850    * difficulty setting. Minimum town rating selected by difficulty level
02851    */
02852   int needed = needed_rating[_settings_game.difficulty.town_council_tolerance][type];
02853 
02854   if (GetRating(t) < needed) {
02855     SetDParam(0, t->index);
02856     _error_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS;
02857     return false;
02858   }
02859 
02860   return true;
02861 }
02862 
02863 void TownsMonthlyLoop()
02864 {
02865   Town *t;
02866 
02867   FOR_ALL_TOWNS(t) {
02868     if (t->road_build_months != 0) t->road_build_months--;
02869 
02870     if (t->exclusive_counter != 0)
02871       if (--t->exclusive_counter == 0) t->exclusivity = INVALID_COMPANY;
02872 
02873     UpdateTownGrowRate(t);
02874     UpdateTownAmounts(t);
02875     UpdateTownUnwanted(t);
02876   }
02877 }
02878 
02879 void TownsYearlyLoop()
02880 {
02881   /* Increment house ages */
02882   for (TileIndex t = 0; t < MapSize(); t++) {
02883     if (!IsTileType(t, MP_HOUSE)) continue;
02884     IncrementHouseAge(t);
02885   }
02886 }
02887 
02888 void InitializeTowns()
02889 {
02890   _town_pool.CleanPool();
02891 }
02892 
02893 static CommandCost TerraformTile_Town(TileIndex tile, DoCommandFlag flags, uint z_new, Slope tileh_new)
02894 {
02895   if (AutoslopeEnabled()) {
02896     HouseID house = GetHouseType(tile);
02897     GetHouseNorthPart(house); // modifies house to the ID of the north tile
02898     const HouseSpec *hs = HouseSpec::Get(house);
02899 
02900     /* Here we differ from TTDP by checking TILE_NOT_SLOPED */
02901     if (((hs->building_flags & TILE_NOT_SLOPED) == 0) && !IsSteepSlope(tileh_new) &&
02902         (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
02903       bool allow_terraform = true;
02904 
02905       /* Call the autosloping callback per tile, not for the whole building at once. */
02906       house = GetHouseType(tile);
02907       hs = HouseSpec::Get(house);
02908       if (HasBit(hs->callback_mask, CBM_HOUSE_AUTOSLOPE)) {
02909         /* If the callback fails, allow autoslope. */
02910         uint16 res = GetHouseCallback(CBID_HOUSE_AUTOSLOPE, 0, 0, house, Town::GetByTile(tile), tile);
02911         if ((res != 0) && (res != CALLBACK_FAILED)) allow_terraform = false;
02912       }
02913 
02914       if (allow_terraform) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
02915     }
02916   }
02917 
02918   return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02919 }
02920 
02922 extern const TileTypeProcs _tile_type_town_procs = {
02923   DrawTile_Town,           // draw_tile_proc
02924   GetSlopeZ_Town,          // get_slope_z_proc
02925   ClearTile_Town,          // clear_tile_proc
02926   AddAcceptedCargo_Town,   // add_accepted_cargo_proc
02927   GetTileDesc_Town,        // get_tile_desc_proc
02928   GetTileTrackStatus_Town, // get_tile_track_status_proc
02929   NULL,                    // click_tile_proc
02930   AnimateTile_Town,        // animate_tile_proc
02931   TileLoop_Town,           // tile_loop_clear
02932   ChangeTileOwner_Town,    // change_tile_owner_clear
02933   AddProducedCargo_Town,   // add_produced_cargo_proc
02934   NULL,                    // vehicle_enter_tile_proc
02935   GetFoundation_Town,      // get_foundation_proc
02936   TerraformTile_Town,      // terraform_tile_proc
02937 };
02938 
02939 
02940 HouseSpec _house_specs[HOUSE_MAX];
02941 
02942 void ResetHouses()
02943 {
02944   memset(&_house_specs, 0, sizeof(_house_specs));
02945   memcpy(&_house_specs, &_original_house_specs, sizeof(_original_house_specs));
02946 
02947   /* Reset any overrides that have been set. */
02948   _house_mngr.ResetOverride();
02949 }

Generated on Tue Sep 14 17:06:56 2010 for OpenTTD by  doxygen 1.6.1