# town_cmd.cpp

Go to the documentation of this file.

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