town_cmd.cpp

Go to the documentation of this file.
00001 /* $Id: town_cmd.cpp 23254 2011-11-18 20:52:13Z rubidium $ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
00006  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
00007  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
00008  */
00009 
00012 #include "stdafx.h"
00013 #include "road_internal.h" /* Cleaning up road bits */
00014 #include "road_cmd.h"
00015 #include "landscape.h"
00016 #include "viewport_func.h"
00017 #include "cmd_helper.h"
00018 #include "command_func.h"
00019 #include "industry.h"
00020 #include "station_base.h"
00021 #include "company_base.h"
00022 #include "news_func.h"
00023 #include "gui.h"
00024 #include "object.h"
00025 #include "genworld.h"
00026 #include "newgrf_debug.h"
00027 #include "newgrf_house.h"
00028 #include "newgrf_text.h"
00029 #include "newgrf_config.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 "animated_tile_func.h"
00038 #include "date_func.h"
00039 #include "subsidy_func.h"
00040 #include "core/pool_func.hpp"
00041 #include "town.h"
00042 #include "townname_func.h"
00043 #include "townname_type.h"
00044 #include "core/random_func.hpp"
00045 #include "core/backup_type.hpp"
00046 #include "depot_base.h"
00047 #include "object_map.h"
00048 #include "object_base.h"
00049 #include "ai/ai.hpp"
00050 
00051 #include "table/strings.h"
00052 #include "table/town_land.h"
00053 
00054 TownID _new_town_id;
00055 
00056 /* Initialize the town-pool */
00057 TownPool _town_pool("Town");
00058 INSTANTIATE_POOL_METHODS(Town)
00059 
00060 Town::~Town()
00061 {
00062   free(this->name);
00063 
00064   if (CleaningPool()) return;
00065 
00066   /* Delete town authority window
00067    * and remove from list of sorted towns */
00068   DeleteWindowById(WC_TOWN_VIEW, this->index);
00069 
00070   /* Check no industry is related to us. */
00071   const Industry *i;
00072   FOR_ALL_INDUSTRIES(i) assert(i->town != this);
00073 
00074   /* ... and no object is related to us. */
00075   const Object *o;
00076   FOR_ALL_OBJECTS(o) assert(o->town != this);
00077 
00078   /* Check no tile is related to us. */
00079   for (TileIndex tile = 0; tile < MapSize(); ++tile) {
00080     switch (GetTileType(tile)) {
00081       case MP_HOUSE:
00082         assert(GetTownIndex(tile) != this->index);
00083         break;
00084 
00085       case MP_ROAD:
00086         assert(!HasTownOwnedRoad(tile) || GetTownIndex(tile) != this->index);
00087         break;
00088 
00089       case MP_TUNNELBRIDGE:
00090         assert(!IsTileOwner(tile, OWNER_TOWN) || ClosestTownFromTile(tile, UINT_MAX) != this);
00091         break;
00092 
00093       default:
00094         break;
00095     }
00096   }
00097 
00098   DeleteSubsidyWith(ST_TOWN, this->index);
00099   DeleteNewGRFInspectWindow(GSF_FAKE_TOWNS, 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   /* Give objects a new home! */
00116   Object *o;
00117   FOR_ALL_OBJECTS(o) {
00118     if (o->town == NULL) o->town = CalcClosestTownFromTile(o->location.tile, UINT_MAX);
00119   }
00120 }
00121 
00125 void Town::InitializeLayout(TownLayout layout)
00126 {
00127   if (layout != TL_RANDOM) {
00128     this->layout = layout;
00129     return;
00130   }
00131 
00132   this->layout = TileHash(TileX(this->xy), TileY(this->xy)) % (NUM_TLS - 1);
00133 }
00134 
00139 /* static */ Town *Town::GetRandom()
00140 {
00141   if (Town::GetNumItems() == 0) return NULL;
00142   int num = RandomRange((uint16)Town::GetNumItems());
00143   size_t index = MAX_UVALUE(size_t);
00144 
00145   while (num >= 0) {
00146     num--;
00147     index++;
00148 
00149     /* Make sure we have a valid town */
00150     while (!Town::IsValidID(index)) {
00151       index++;
00152       assert(index < Town::GetPoolSize());
00153     }
00154   }
00155 
00156   return Town::Get(index);
00157 }
00158 
00163 Money HouseSpec::GetRemovalCost() const
00164 {
00165   return (_price[PR_CLEAR_HOUSE] * this->removal_cost) >> 8;
00166 }
00167 
00168 // Local
00169 static int _grow_town_result;
00170 
00171 /* Describe the possible states */
00172 enum TownGrowthResult {
00173   GROWTH_SUCCEED         = -1,
00174   GROWTH_SEARCH_STOPPED  =  0
00175 //  GROWTH_SEARCH_RUNNING >=  1
00176 };
00177 
00178 static bool BuildTownHouse(Town *t, TileIndex tile);
00179 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout);
00180 
00181 static void TownDrawHouseLift(const TileInfo *ti)
00182 {
00183   AddChildSpriteScreen(SPR_LIFT, PAL_NONE, 14, 60 - GetLiftPosition(ti->tile));
00184 }
00185 
00186 typedef void TownDrawTileProc(const TileInfo *ti);
00187 static TownDrawTileProc * const _town_draw_tile_procs[1] = {
00188   TownDrawHouseLift
00189 };
00190 
00196 static inline DiagDirection RandomDiagDir()
00197 {
00198   return (DiagDirection)(3 & Random());
00199 }
00200 
00206 static void DrawTile_Town(TileInfo *ti)
00207 {
00208   HouseID house_id = GetHouseType(ti->tile);
00209 
00210   if (house_id >= NEW_HOUSE_OFFSET) {
00211     /* Houses don't necessarily need new graphics. If they don't have a
00212      * spritegroup associated with them, then the sprite for the substitute
00213      * house id is drawn instead. */
00214     if (HouseSpec::Get(house_id)->grf_prop.spritegroup[0] != NULL) {
00215       DrawNewHouseTile(ti, house_id);
00216       return;
00217     } else {
00218       house_id = HouseSpec::Get(house_id)->grf_prop.subst_id;
00219     }
00220   }
00221 
00222   /* Retrieve pointer to the draw town tile struct */
00223   const DrawBuildingsTileStruct *dcts = &_town_draw_tile_data[house_id << 4 | TileHash2Bit(ti->x, ti->y) << 2 | GetHouseBuildingStage(ti->tile)];
00224 
00225   if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
00226 
00227   DrawGroundSprite(dcts->ground.sprite, dcts->ground.pal);
00228 
00229   /* If houses are invisible, do not draw the upper part */
00230   if (IsInvisibilitySet(TO_HOUSES)) return;
00231 
00232   /* Add a house on top of the ground? */
00233   SpriteID image = dcts->building.sprite;
00234   if (image != 0) {
00235     AddSortableSpriteToDraw(image, dcts->building.pal,
00236       ti->x + dcts->subtile_x,
00237       ti->y + dcts->subtile_y,
00238       dcts->width,
00239       dcts->height,
00240       dcts->dz,
00241       ti->z,
00242       IsTransparencySet(TO_HOUSES)
00243     );
00244 
00245     if (IsTransparencySet(TO_HOUSES)) return;
00246   }
00247 
00248   {
00249     int proc = dcts->draw_proc - 1;
00250 
00251     if (proc >= 0) _town_draw_tile_procs[proc](ti);
00252   }
00253 }
00254 
00255 static uint GetSlopeZ_Town(TileIndex tile, uint x, uint y)
00256 {
00257   return GetTileMaxZ(tile);
00258 }
00259 
00261 static Foundation GetFoundation_Town(TileIndex tile, Slope tileh)
00262 {
00263   HouseID hid = GetHouseType(tile);
00264 
00265   /* For NewGRF house tiles we might not be drawing a foundation. We need to
00266    * account for this, as other structures should
00267    * draw the wall of the foundation in this case.
00268    */
00269   if (hid >= NEW_HOUSE_OFFSET) {
00270     const HouseSpec *hs = HouseSpec::Get(hid);
00271     if (hs->grf_prop.spritegroup[0] != NULL && HasBit(hs->callback_mask, CBM_HOUSE_DRAW_FOUNDATIONS)) {
00272       uint32 callback_res = GetHouseCallback(CBID_HOUSE_DRAW_FOUNDATIONS, 0, 0, hid, Town::GetByTile(tile), tile);
00273       if (callback_res == 0) return FOUNDATION_NONE;
00274     }
00275   }
00276   return FlatteningFoundation(tileh);
00277 }
00278 
00285 static void AnimateTile_Town(TileIndex tile)
00286 {
00287   if (GetHouseType(tile) >= NEW_HOUSE_OFFSET) {
00288     AnimateNewHouseTile(tile);
00289     return;
00290   }
00291 
00292   if (_tick_counter & 3) return;
00293 
00294   /* If the house is not one with a lift anymore, then stop this animating.
00295    * Not exactly sure when this happens, but probably when a house changes.
00296    * Before this was just a return...so it'd leak animated tiles..
00297    * That bug seems to have been here since day 1?? */
00298   if (!(HouseSpec::Get(GetHouseType(tile))->building_flags & BUILDING_IS_ANIMATED)) {
00299     DeleteAnimatedTile(tile);
00300     return;
00301   }
00302 
00303   if (!LiftHasDestination(tile)) {
00304     uint i;
00305 
00306     /* Building has 6 floors, number 0 .. 6, where 1 is illegal.
00307      * This is due to the fact that the first floor is, in the graphics,
00308      *  the height of 2 'normal' floors.
00309      * Furthermore, there are 6 lift positions from floor N (incl) to floor N + 1 (excl) */
00310     do {
00311       i = RandomRange(7);
00312     } while (i == 1 || i * 6 == GetLiftPosition(tile));
00313 
00314     SetLiftDestination(tile, i);
00315   }
00316 
00317   int pos = GetLiftPosition(tile);
00318   int dest = GetLiftDestination(tile) * 6;
00319   pos += (pos < dest) ? 1 : -1;
00320   SetLiftPosition(tile, pos);
00321 
00322   if (pos == dest) {
00323     HaltLift(tile);
00324     DeleteAnimatedTile(tile);
00325   }
00326 
00327   MarkTileDirtyByTile(tile);
00328 }
00329 
00336 static bool IsCloseToTown(TileIndex tile, uint dist)
00337 {
00338   const Town *t;
00339 
00340   FOR_ALL_TOWNS(t) {
00341     if (DistanceManhattan(tile, t->xy) < dist) return true;
00342   }
00343   return false;
00344 }
00345 
00350 void Town::UpdateVirtCoord()
00351 {
00352   Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
00353   SetDParam(0, this->index);
00354   SetDParam(1, this->population);
00355   this->sign.UpdatePosition(pt.x, pt.y - 24,
00356     _settings_client.gui.population_in_label ? STR_VIEWPORT_TOWN_POP : STR_VIEWPORT_TOWN);
00357 
00358   SetWindowDirty(WC_TOWN_VIEW, this->index);
00359 }
00360 
00362 void UpdateAllTownVirtCoords()
00363 {
00364   Town *t;
00365 
00366   FOR_ALL_TOWNS(t) {
00367     t->UpdateVirtCoord();
00368   }
00369 }
00370 
00376 static void ChangePopulation(Town *t, int mod)
00377 {
00378   t->population += mod;
00379   SetWindowDirty(WC_TOWN_VIEW, t->index);
00380   t->UpdateVirtCoord();
00381 
00382   InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
00383 }
00384 
00390 uint32 GetWorldPopulation()
00391 {
00392   uint32 pop = 0;
00393   const Town *t;
00394 
00395   FOR_ALL_TOWNS(t) pop += t->population;
00396   return pop;
00397 }
00398 
00403 static void MakeSingleHouseBigger(TileIndex tile)
00404 {
00405   assert(IsTileType(tile, MP_HOUSE));
00406 
00407   /* progress in construction stages */
00408   IncHouseConstructionTick(tile);
00409   if (GetHouseConstructionTick(tile) != 0) return;
00410 
00411   AnimateNewHouseConstruction(tile);
00412 
00413   if (IsHouseCompleted(tile)) {
00414     /* Now that construction is complete, we can add the population of the
00415      * building to the town. */
00416     ChangePopulation(Town::GetByTile(tile), HouseSpec::Get(GetHouseType(tile))->population);
00417     ResetHouseAge(tile);
00418   }
00419   MarkTileDirtyByTile(tile);
00420 }
00421 
00426 static void MakeTownHouseBigger(TileIndex tile)
00427 {
00428   uint flags = HouseSpec::Get(GetHouseType(tile))->building_flags;
00429   if (flags & BUILDING_HAS_1_TILE)  MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 0));
00430   if (flags & BUILDING_2_TILES_Y)   MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 1));
00431   if (flags & BUILDING_2_TILES_X)   MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 0));
00432   if (flags & BUILDING_HAS_4_TILES) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 1));
00433 }
00434 
00441 static void TileLoop_Town(TileIndex tile)
00442 {
00443   HouseID house_id = GetHouseType(tile);
00444 
00445   /* NewHouseTileLoop returns false if Callback 21 succeeded, i.e. the house
00446    * doesn't exist any more, so don't continue here. */
00447   if (house_id >= NEW_HOUSE_OFFSET && !NewHouseTileLoop(tile)) return;
00448 
00449   if (!IsHouseCompleted(tile)) {
00450     /* Construction is not completed. See if we can go further in construction*/
00451     MakeTownHouseBigger(tile);
00452     return;
00453   }
00454 
00455   const HouseSpec *hs = HouseSpec::Get(house_id);
00456 
00457   /* If the lift has a destination, it is already an animated tile. */
00458   if ((hs->building_flags & BUILDING_IS_ANIMATED) &&
00459       house_id < NEW_HOUSE_OFFSET &&
00460       !LiftHasDestination(tile) &&
00461       Chance16(1, 2)) {
00462     AddAnimatedTile(tile);
00463   }
00464 
00465   Town *t = Town::GetByTile(tile);
00466   uint32 r = Random();
00467 
00468   StationFinder stations(TileArea(tile, 1, 1));
00469 
00470   if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
00471     for (uint i = 0; i < 256; i++) {
00472       uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, r, house_id, t, tile);
00473 
00474       if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
00475 
00476       CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
00477       if (cargo == CT_INVALID) continue;
00478 
00479       uint amt = GB(callback, 0, 8);
00480       if (amt == 0) continue;
00481 
00482       uint moved = MoveGoodsToStation(cargo, amt, ST_TOWN, t->index, stations.GetStations());
00483 
00484       const CargoSpec *cs = CargoSpec::Get(cargo);
00485       switch (cs->town_effect) {
00486         case TE_PASSENGERS:
00487           t->new_max_pass += amt;
00488           t->new_act_pass += moved;
00489           break;
00490 
00491         case TE_MAIL:
00492           t->new_max_mail += amt;
00493           t->new_act_mail += moved;
00494           break;
00495 
00496         default:
00497           break;
00498       }
00499     }
00500   } else {
00501     if (GB(r, 0, 8) < hs->population) {
00502       uint amt = GB(r, 0, 8) / 8 + 1;
00503 
00504       if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
00505       t->new_max_pass += amt;
00506       t->new_act_pass += MoveGoodsToStation(CT_PASSENGERS, amt, ST_TOWN, t->index, stations.GetStations());
00507     }
00508 
00509     if (GB(r, 8, 8) < hs->mail_generation) {
00510       uint amt = GB(r, 8, 8) / 8 + 1;
00511 
00512       if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
00513       t->new_max_mail += amt;
00514       t->new_act_mail += MoveGoodsToStation(CT_MAIL, amt, ST_TOWN, t->index, stations.GetStations());
00515     }
00516   }
00517 
00518   Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
00519 
00520   if ((hs->building_flags & BUILDING_HAS_1_TILE) &&
00521       HasBit(t->flags, TOWN_IS_FUNDED) &&
00522       CanDeleteHouse(tile) &&
00523       GetHouseAge(tile) >= hs->minimum_life &&
00524       --t->time_until_rebuild == 0) {
00525     t->time_until_rebuild = GB(r, 16, 8) + 192;
00526 
00527     ClearTownHouse(t, tile);
00528 
00529     /* Rebuild with another house? */
00530     if (GB(r, 24, 8) >= 12) BuildTownHouse(t, tile);
00531   }
00532 
00533   cur_company.Restore();
00534 }
00535 
00536 static CommandCost ClearTile_Town(TileIndex tile, DoCommandFlag flags)
00537 {
00538   if (flags & DC_AUTO) return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
00539   if (!CanDeleteHouse(tile)) return CMD_ERROR;
00540 
00541   const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
00542 
00543   CommandCost cost(EXPENSES_CONSTRUCTION);
00544   cost.AddCost(hs->GetRemovalCost());
00545 
00546   int rating = hs->remove_rating_decrease;
00547   Town *t = Town::GetByTile(tile);
00548 
00549   if (Company::IsValidID(_current_company)) {
00550     if (rating > t->ratings[_current_company] && !(flags & DC_NO_TEST_TOWN_RATING) && !_cheats.magic_bulldozer.value) {
00551       SetDParam(0, t->index);
00552       return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
00553     }
00554   }
00555 
00556   ChangeTownRating(t, -rating, RATING_HOUSE_MINIMUM, flags);
00557   if (flags & DC_EXEC) {
00558     ClearTownHouse(t, tile);
00559   }
00560 
00561   return cost;
00562 }
00563 
00564 static void AddProducedCargo_Town(TileIndex tile, CargoArray &produced)
00565 {
00566   HouseID house_id = GetHouseType(tile);
00567   const HouseSpec *hs = HouseSpec::Get(house_id);
00568   Town *t = Town::GetByTile(tile);
00569 
00570   if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
00571     for (uint i = 0; i < 256; i++) {
00572       uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, 0, house_id, t, tile);
00573 
00574       if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
00575 
00576       CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
00577 
00578       if (cargo == CT_INVALID) continue;
00579       produced[cargo]++;
00580     }
00581   } else {
00582     if (hs->population > 0) {
00583       produced[CT_PASSENGERS]++;
00584     }
00585     if (hs->mail_generation > 0) {
00586       produced[CT_MAIL]++;
00587     }
00588   }
00589 }
00590 
00591 static inline void AddAcceptedCargoSetMask(CargoID cargo, uint amount, CargoArray &acceptance, uint32 *always_accepted)
00592 {
00593   if (cargo == CT_INVALID || amount == 0) return;
00594   acceptance[cargo] += amount;
00595   SetBit(*always_accepted, cargo);
00596 }
00597 
00598 static void AddAcceptedCargo_Town(TileIndex tile, CargoArray &acceptance, uint32 *always_accepted)
00599 {
00600   const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
00601   CargoID accepts[3];
00602 
00603   /* Set the initial accepted cargo types */
00604   for (uint8 i = 0; i < lengthof(accepts); i++) {
00605     accepts[i] = hs->accepts_cargo[i];
00606   }
00607 
00608   /* Check for custom accepted cargo types */
00609   if (HasBit(hs->callback_mask, CBM_HOUSE_ACCEPT_CARGO)) {
00610     uint16 callback = GetHouseCallback(CBID_HOUSE_ACCEPT_CARGO, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
00611     if (callback != CALLBACK_FAILED) {
00612       /* Replace accepted cargo types with translated values from callback */
00613       accepts[0] = GetCargoTranslation(GB(callback,  0, 5), hs->grf_prop.grffile);
00614       accepts[1] = GetCargoTranslation(GB(callback,  5, 5), hs->grf_prop.grffile);
00615       accepts[2] = GetCargoTranslation(GB(callback, 10, 5), hs->grf_prop.grffile);
00616     }
00617   }
00618 
00619   /* Check for custom cargo acceptance */
00620   if (HasBit(hs->callback_mask, CBM_HOUSE_CARGO_ACCEPTANCE)) {
00621     uint16 callback = GetHouseCallback(CBID_HOUSE_CARGO_ACCEPTANCE, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
00622     if (callback != CALLBACK_FAILED) {
00623       AddAcceptedCargoSetMask(accepts[0], GB(callback, 0, 4), acceptance, always_accepted);
00624       AddAcceptedCargoSetMask(accepts[1], GB(callback, 4, 4), acceptance, always_accepted);
00625       if (_settings_game.game_creation.landscape != LT_TEMPERATE && HasBit(callback, 12)) {
00626         /* The 'S' bit indicates food instead of goods */
00627         AddAcceptedCargoSetMask(CT_FOOD, GB(callback, 8, 4), acceptance, always_accepted);
00628       } else {
00629         AddAcceptedCargoSetMask(accepts[2], GB(callback, 8, 4), acceptance, always_accepted);
00630       }
00631       return;
00632     }
00633   }
00634 
00635   /* No custom acceptance, so fill in with the default values */
00636   for (uint8 i = 0; i < lengthof(accepts); i++) {
00637     AddAcceptedCargoSetMask(accepts[i], hs->cargo_acceptance[i], acceptance, always_accepted);
00638   }
00639 }
00640 
00641 static void GetTileDesc_Town(TileIndex tile, TileDesc *td)
00642 {
00643   const HouseID house = GetHouseType(tile);
00644   const HouseSpec *hs = HouseSpec::Get(house);
00645   bool house_completed = IsHouseCompleted(tile);
00646 
00647   td->str = hs->building_name;
00648 
00649   uint16 callback_res = GetHouseCallback(CBID_HOUSE_CUSTOM_NAME, house_completed ? 1 : 0, 0, house, Town::GetByTile(tile), tile);
00650   if (callback_res != CALLBACK_FAILED) {
00651     StringID new_name = GetGRFStringID(hs->grf_prop.grffile->grfid, 0xD000 + callback_res);
00652     if (new_name != STR_NULL && new_name != STR_UNDEFINED) {
00653       td->str = new_name;
00654     }
00655   }
00656 
00657   if (!house_completed) {
00658     SetDParamX(td->dparam, 0, td->str);
00659     td->str = STR_LAI_TOWN_INDUSTRY_DESCRIPTION_UNDER_CONSTRUCTION;
00660   }
00661 
00662   if (hs->grf_prop.grffile != NULL) {
00663     const GRFConfig *gc = GetGRFConfig(hs->grf_prop.grffile->grfid);
00664     td->grf = gc->GetName();
00665   }
00666 
00667   td->owner[0] = OWNER_TOWN;
00668 }
00669 
00670 static TrackStatus GetTileTrackStatus_Town(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
00671 {
00672   /* not used */
00673   return 0;
00674 }
00675 
00676 static void ChangeTileOwner_Town(TileIndex tile, Owner old_owner, Owner new_owner)
00677 {
00678   /* not used */
00679 }
00680 
00681 static bool GrowTown(Town *t);
00682 
00683 static void TownTickHandler(Town *t)
00684 {
00685   if (HasBit(t->flags, TOWN_IS_FUNDED)) {
00686     int i = t->grow_counter - 1;
00687     if (i < 0) {
00688       if (GrowTown(t)) {
00689         i = t->growth_rate;
00690       } else {
00691         i = 0;
00692       }
00693     }
00694     t->grow_counter = i;
00695   }
00696 
00697   UpdateTownRadius(t);
00698 }
00699 
00700 void OnTick_Town()
00701 {
00702   if (_game_mode == GM_EDITOR) return;
00703 
00704   Town *t;
00705   FOR_ALL_TOWNS(t) {
00706     /* Run town tick at regular intervals, but not all at once. */
00707     if ((_tick_counter + t->index) % TOWN_GROWTH_FREQUENCY == 0) {
00708       TownTickHandler(t);
00709     }
00710   }
00711 }
00712 
00721 static RoadBits GetTownRoadBits(TileIndex tile)
00722 {
00723   if (IsRoadDepotTile(tile) || IsStandardRoadStopTile(tile)) return ROAD_NONE;
00724 
00725   return GetAnyRoadBits(tile, ROADTYPE_ROAD, true);
00726 }
00727 
00738 static bool IsNeighborRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
00739 {
00740   if (!IsValidTile(tile)) return false;
00741 
00742   /* Lookup table for the used diff values */
00743   const TileIndexDiff tid_lt[3] = {
00744     TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90RIGHT)),
00745     TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90LEFT)),
00746     TileOffsByDiagDir(ReverseDiagDir(dir)),
00747   };
00748 
00749   dist_multi = (dist_multi + 1) * 4;
00750   for (uint pos = 4; pos < dist_multi; pos++) {
00751     /* Go (pos / 4) tiles to the left or the right */
00752     TileIndexDiff cur = tid_lt[(pos & 1) ? 0 : 1] * (pos / 4);
00753 
00754     /* Use the current tile as origin, or go one tile backwards */
00755     if (pos & 2) cur += tid_lt[2];
00756 
00757     /* Test for roadbit parallel to dir and facing towards the middle axis */
00758     if (IsValidTile(tile + cur) &&
00759         GetTownRoadBits(TILE_ADD(tile, cur)) & DiagDirToRoadBits((pos & 2) ? dir : ReverseDiagDir(dir))) return true;
00760   }
00761   return false;
00762 }
00763 
00772 static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
00773 {
00774   if (DistanceFromEdge(tile) == 0) return false;
00775 
00776   Slope cur_slope, desired_slope;
00777 
00778   for (;;) {
00779     /* Check if there already is a road at this point? */
00780     if (GetTownRoadBits(tile) == ROAD_NONE) {
00781       /* No, try if we are able to build a road piece there.
00782        * If that fails clear the land, and if that fails exit.
00783        * This is to make sure that we can build a road here later. */
00784       if (DoCommand(tile, ((dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? ROAD_Y : ROAD_X), 0, DC_AUTO, CMD_BUILD_ROAD).Failed() &&
00785           DoCommand(tile, 0, 0, DC_AUTO, CMD_LANDSCAPE_CLEAR).Failed())
00786         return false;
00787     }
00788 
00789     cur_slope = _settings_game.construction.build_on_slopes ? GetFoundationSlope(tile, NULL) : GetTileSlope(tile, NULL);
00790     bool ret = !IsNeighborRoadTile(tile, dir, t->layout == TL_ORIGINAL ? 1 : 2);
00791     if (cur_slope == SLOPE_FLAT) return ret;
00792 
00793     /* If the tile is not a slope in the right direction, then
00794      * maybe terraform some. */
00795     desired_slope = (dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? SLOPE_NW : SLOPE_NE;
00796     if (desired_slope != cur_slope && ComplementSlope(desired_slope) != cur_slope) {
00797       if (Chance16(1, 8)) {
00798         CommandCost res = CMD_ERROR;
00799         if (!_generating_world && Chance16(1, 10)) {
00800           /* Note: Do not replace "^ SLOPE_ELEVATED" with ComplementSlope(). The slope might be steep. */
00801           res = DoCommand(tile, Chance16(1, 16) ? cur_slope : cur_slope ^ SLOPE_ELEVATED, 0,
00802               DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
00803         }
00804         if (res.Failed() && Chance16(1, 3)) {
00805           /* We can consider building on the slope, though. */
00806           return ret;
00807         }
00808       }
00809       return false;
00810     }
00811     return ret;
00812   }
00813 }
00814 
00815 static bool TerraformTownTile(TileIndex tile, int edges, int dir)
00816 {
00817   assert(tile < MapSize());
00818 
00819   CommandCost r = DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
00820   if (r.Failed() || r.GetCost() >= (_price[PR_TERRAFORM] + 2) * 8) return false;
00821   DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER | DC_EXEC, CMD_TERRAFORM_LAND);
00822   return true;
00823 }
00824 
00825 static void LevelTownLand(TileIndex tile)
00826 {
00827   assert(tile < MapSize());
00828 
00829   /* Don't terraform if land is plain or if there's a house there. */
00830   if (IsTileType(tile, MP_HOUSE)) return;
00831   Slope tileh = GetTileSlope(tile, NULL);
00832   if (tileh == SLOPE_FLAT) return;
00833 
00834   /* First try up, then down */
00835   if (!TerraformTownTile(tile, ~tileh & SLOPE_ELEVATED, 1)) {
00836     TerraformTownTile(tile, tileh & SLOPE_ELEVATED, 0);
00837   }
00838 }
00839 
00849 static RoadBits GetTownRoadGridElement(Town *t, TileIndex tile, DiagDirection dir)
00850 {
00851   /* align the grid to the downtown */
00852   TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile); // Vector from downtown to the tile
00853   RoadBits rcmd = ROAD_NONE;
00854 
00855   switch (t->layout) {
00856     default: NOT_REACHED();
00857 
00858     case TL_2X2_GRID:
00859       if ((grid_pos.x % 3) == 0) rcmd |= ROAD_Y;
00860       if ((grid_pos.y % 3) == 0) rcmd |= ROAD_X;
00861       break;
00862 
00863     case TL_3X3_GRID:
00864       if ((grid_pos.x % 4) == 0) rcmd |= ROAD_Y;
00865       if ((grid_pos.y % 4) == 0) rcmd |= ROAD_X;
00866       break;
00867   }
00868 
00869   /* Optimise only X-junctions */
00870   if (rcmd != ROAD_ALL) return rcmd;
00871 
00872   RoadBits rb_template;
00873 
00874   switch (GetTileSlope(tile, NULL)) {
00875     default:       rb_template = ROAD_ALL; break;
00876     case SLOPE_W:  rb_template = ROAD_NW | ROAD_SW; break;
00877     case SLOPE_SW: rb_template = ROAD_Y  | ROAD_SW; break;
00878     case SLOPE_S:  rb_template = ROAD_SW | ROAD_SE; break;
00879     case SLOPE_SE: rb_template = ROAD_X  | ROAD_SE; break;
00880     case SLOPE_E:  rb_template = ROAD_SE | ROAD_NE; break;
00881     case SLOPE_NE: rb_template = ROAD_Y  | ROAD_NE; break;
00882     case SLOPE_N:  rb_template = ROAD_NE | ROAD_NW; break;
00883     case SLOPE_NW: rb_template = ROAD_X  | ROAD_NW; break;
00884     case SLOPE_STEEP_W:
00885     case SLOPE_STEEP_S:
00886     case SLOPE_STEEP_E:
00887     case SLOPE_STEEP_N:
00888       rb_template = ROAD_NONE;
00889       break;
00890   }
00891 
00892   /* Stop if the template is compatible to the growth dir */
00893   if (DiagDirToRoadBits(ReverseDiagDir(dir)) & rb_template) return rb_template;
00894   /* If not generate a straight road in the direction of the growth */
00895   return DiagDirToRoadBits(dir) | DiagDirToRoadBits(ReverseDiagDir(dir));
00896 }
00897 
00908 static bool GrowTownWithExtraHouse(Town *t, TileIndex tile)
00909 {
00910   /* We can't look further than that. */
00911   if (DistanceFromEdge(tile) == 0) return false;
00912 
00913   uint counter = 0; // counts the house neighbor tiles
00914 
00915   /* Check the tiles E,N,W and S of the current tile for houses */
00916   for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
00917     /* Count both void and house tiles for checking whether there
00918      * are enough houses in the area. This to make it likely that
00919      * houses get build up to the edge of the map. */
00920     switch (GetTileType(TileAddByDiagDir(tile, dir))) {
00921       case MP_HOUSE:
00922       case MP_VOID:
00923         counter++;
00924         break;
00925 
00926       default:
00927         break;
00928     }
00929 
00930     /* If there are enough neighbors stop here */
00931     if (counter >= 3) {
00932       if (BuildTownHouse(t, tile)) {
00933         _grow_town_result = GROWTH_SUCCEED;
00934         return true;
00935       }
00936       return false;
00937     }
00938   }
00939   return false;
00940 }
00941 
00950 static bool GrowTownWithRoad(const Town *t, TileIndex tile, RoadBits rcmd)
00951 {
00952   if (DoCommand(tile, rcmd, t->index, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD).Succeeded()) {
00953     _grow_town_result = GROWTH_SUCCEED;
00954     return true;
00955   }
00956   return false;
00957 }
00958 
00969 static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
00970 {
00971   assert(bridge_dir < DIAGDIR_END);
00972 
00973   const Slope slope = GetTileSlope(tile, NULL);
00974   if (slope == SLOPE_FLAT) return false; // no slope, no bridge
00975 
00976   /* Make sure the direction is compatible with the slope.
00977    * Well we check if the slope has an up bit set in the
00978    * reverse direction. */
00979   if (slope & InclinedSlope(bridge_dir)) return false;
00980 
00981   /* Assure that the bridge is connectable to the start side */
00982   if (!(GetTownRoadBits(TileAddByDiagDir(tile, ReverseDiagDir(bridge_dir))) & DiagDirToRoadBits(bridge_dir))) return false;
00983 
00984   /* We are in the right direction */
00985   uint8 bridge_length = 0;      // This value stores the length of the possible bridge
00986   TileIndex bridge_tile = tile; // Used to store the other waterside
00987 
00988   const int delta = TileOffsByDiagDir(bridge_dir);
00989   do {
00990     if (bridge_length++ >= 11) {
00991       /* Max 11 tile long bridges */
00992       return false;
00993     }
00994     bridge_tile += delta;
00995   } while (TileX(bridge_tile) != 0 && TileY(bridge_tile) != 0 && IsWaterTile(bridge_tile));
00996 
00997   /* no water tiles in between? */
00998   if (bridge_length == 1) return false;
00999 
01000   for (uint8 times = 0; times <= 22; times++) {
01001     byte bridge_type = RandomRange(MAX_BRIDGES - 1);
01002 
01003     /* Can we actually build the bridge? */
01004     if (DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)), CMD_BUILD_BRIDGE).Succeeded()) {
01005       DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, DC_EXEC | CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)), CMD_BUILD_BRIDGE);
01006       _grow_town_result = GROWTH_SUCCEED;
01007       return true;
01008     }
01009   }
01010   /* Quit if it selecting an appropiate bridge type fails a large number of times. */
01011   return false;
01012 }
01013 
01031 static void GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1)
01032 {
01033   RoadBits rcmd = ROAD_NONE;  // RoadBits for the road construction command
01034   TileIndex tile = *tile_ptr; // The main tile on which we base our growth
01035 
01036   assert(tile < MapSize());
01037 
01038   if (cur_rb == ROAD_NONE) {
01039     /* Tile has no road. First reset the status counter
01040      * to say that this is the last iteration. */
01041     _grow_town_result = GROWTH_SEARCH_STOPPED;
01042 
01043     if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
01044     if (!_settings_game.economy.allow_town_level_crossings && IsTileType(tile, MP_RAILWAY)) return;
01045 
01046     /* Remove hills etc */
01047     if (!_settings_game.construction.build_on_slopes || Chance16(1, 6)) LevelTownLand(tile);
01048 
01049     /* Is a road allowed here? */
01050     switch (t1->layout) {
01051       default: NOT_REACHED();
01052 
01053       case TL_3X3_GRID:
01054       case TL_2X2_GRID:
01055         rcmd = GetTownRoadGridElement(t1, tile, target_dir);
01056         if (rcmd == ROAD_NONE) return;
01057         break;
01058 
01059       case TL_BETTER_ROADS:
01060       case TL_ORIGINAL:
01061         if (!IsRoadAllowedHere(t1, tile, target_dir)) return;
01062 
01063         DiagDirection source_dir = ReverseDiagDir(target_dir);
01064 
01065         if (Chance16(1, 4)) {
01066           /* Randomize a new target dir */
01067           do target_dir = RandomDiagDir(); while (target_dir == source_dir);
01068         }
01069 
01070         if (!IsRoadAllowedHere(t1, TileAddByDiagDir(tile, target_dir), target_dir)) {
01071           /* A road is not allowed to continue the randomized road,
01072            *  return if the road we're trying to build is curved. */
01073           if (target_dir != ReverseDiagDir(source_dir)) return;
01074 
01075           /* Return if neither side of the new road is a house */
01076           if (!IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90RIGHT)), MP_HOUSE) &&
01077               !IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90LEFT)), MP_HOUSE)) {
01078             return;
01079           }
01080 
01081           /* That means that the road is only allowed if there is a house
01082            *  at any side of the new road. */
01083         }
01084 
01085         rcmd = DiagDirToRoadBits(target_dir) | DiagDirToRoadBits(source_dir);
01086         break;
01087     }
01088 
01089   } else if (target_dir < DIAGDIR_END && !(cur_rb & DiagDirToRoadBits(ReverseDiagDir(target_dir)))) {
01090     /* Continue building on a partial road.
01091      * Should be allways OK, so we only generate
01092      * the fitting RoadBits */
01093     _grow_town_result = GROWTH_SEARCH_STOPPED;
01094 
01095     if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
01096 
01097     switch (t1->layout) {
01098       default: NOT_REACHED();
01099 
01100       case TL_3X3_GRID:
01101       case TL_2X2_GRID:
01102         rcmd = GetTownRoadGridElement(t1, tile, target_dir);
01103         break;
01104 
01105       case TL_BETTER_ROADS:
01106       case TL_ORIGINAL:
01107         rcmd = DiagDirToRoadBits(ReverseDiagDir(target_dir));
01108         break;
01109     }
01110   } else {
01111     bool allow_house = true; // Value which decides if we want to construct a house
01112 
01113     /* Reached a tunnel/bridge? Then continue at the other side of it, unless
01114      * it is the starting tile. Half the time, we stay on this side then.*/
01115     if (IsTileType(tile, MP_TUNNELBRIDGE)) {
01116       if (GetTunnelBridgeTransportType(tile) == TRANSPORT_ROAD && (target_dir != DIAGDIR_END || Chance16(1, 2))) {
01117         *tile_ptr = GetOtherTunnelBridgeEnd(tile);
01118       }
01119       return;
01120     }
01121 
01122     /* Possibly extend the road in a direction.
01123      * Randomize a direction and if it has a road, bail out. */
01124     target_dir = RandomDiagDir();
01125     if (cur_rb & DiagDirToRoadBits(target_dir)) return;
01126 
01127     /* This is the tile we will reach if we extend to this direction. */
01128     TileIndex house_tile = TileAddByDiagDir(tile, target_dir); // position of a possible house
01129 
01130     /* Don't walk into water. */
01131     if (HasTileWaterGround(house_tile)) return;
01132 
01133     if (!IsValidTile(house_tile)) return;
01134 
01135     if (_settings_game.economy.allow_town_roads || _generating_world) {
01136       switch (t1->layout) {
01137         default: NOT_REACHED();
01138 
01139         case TL_3X3_GRID: // Use 2x2 grid afterwards!
01140           GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
01141           /* FALL THROUGH */
01142 
01143         case TL_2X2_GRID:
01144           rcmd = GetTownRoadGridElement(t1, house_tile, target_dir);
01145           allow_house = (rcmd == ROAD_NONE);
01146           break;
01147 
01148         case TL_BETTER_ROADS: // Use original afterwards!
01149           GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
01150           /* FALL THROUGH */
01151 
01152         case TL_ORIGINAL:
01153           /* Allow a house at the edge. 60% chance or
01154            * always ok if no road allowed. */
01155           rcmd = DiagDirToRoadBits(target_dir);
01156           allow_house = (!IsRoadAllowedHere(t1, house_tile, target_dir) || Chance16(6, 10));
01157           break;
01158       }
01159     }
01160 
01161     if (allow_house) {
01162       /* Build a house, but not if there already is a house there. */
01163       if (!IsTileType(house_tile, MP_HOUSE)) {
01164         /* Level the land if possible */
01165         if (Chance16(1, 6)) LevelTownLand(house_tile);
01166 
01167         /* And build a house.
01168          * Set result to -1 if we managed to build it. */
01169         if (BuildTownHouse(t1, house_tile)) {
01170           _grow_town_result = GROWTH_SUCCEED;
01171         }
01172       }
01173       return;
01174     }
01175 
01176     _grow_town_result = GROWTH_SEARCH_STOPPED;
01177   }
01178 
01179   /* Return if a water tile */
01180   if (HasTileWaterGround(tile)) return;
01181 
01182   /* Make the roads look nicer */
01183   rcmd = CleanUpRoadBits(tile, rcmd);
01184   if (rcmd == ROAD_NONE) return;
01185 
01186   /* Only use the target direction for bridges to ensure they're connected.
01187    * The target_dir is as computed previously according to town layout, so
01188    * it will match it perfectly. */
01189   if (GrowTownWithBridge(t1, tile, target_dir)) return;
01190 
01191   GrowTownWithRoad(t1, tile, rcmd);
01192 }
01193 
01200 static int GrowTownAtRoad(Town *t, TileIndex tile)
01201 {
01202   /* Special case.
01203    * @see GrowTownInTile Check the else if
01204    */
01205   DiagDirection target_dir = DIAGDIR_END; // The direction in which we want to extend the town
01206 
01207   assert(tile < MapSize());
01208 
01209   /* Number of times to search.
01210    * Better roads, 2X2 and 3X3 grid grow quite fast so we give
01211    * them a little handicap. */
01212   switch (t->layout) {
01213     case TL_BETTER_ROADS:
01214       _grow_town_result = 10 + t->num_houses * 2 / 9;
01215       break;
01216 
01217     case TL_3X3_GRID:
01218     case TL_2X2_GRID:
01219       _grow_town_result = 10 + t->num_houses * 1 / 9;
01220       break;
01221 
01222     default:
01223       _grow_town_result = 10 + t->num_houses * 4 / 9;
01224       break;
01225   }
01226 
01227   do {
01228     RoadBits cur_rb = GetTownRoadBits(tile); // The RoadBits of the current tile
01229 
01230     /* Try to grow the town from this point */
01231     GrowTownInTile(&tile, cur_rb, target_dir, t);
01232 
01233     /* Exclude the source position from the bitmask
01234      * and return if no more road blocks available */
01235     cur_rb &= ~DiagDirToRoadBits(ReverseDiagDir(target_dir));
01236     if (cur_rb == ROAD_NONE) {
01237       return _grow_town_result;
01238     }
01239 
01240     if (IsTileType(tile, MP_TUNNELBRIDGE)) {
01241       /* Only build in the direction away from the tunnel or bridge. */
01242       target_dir = ReverseDiagDir(GetTunnelBridgeDirection(tile));
01243     } else {
01244       /* Select a random bit from the blockmask, walk a step
01245        * and continue the search from there. */
01246       do target_dir = RandomDiagDir(); while (!(cur_rb & DiagDirToRoadBits(target_dir)));
01247     }
01248     tile = TileAddByDiagDir(tile, target_dir);
01249 
01250     if (IsTileType(tile, MP_ROAD) && !IsRoadDepot(tile) && HasTileRoadType(tile, ROADTYPE_ROAD)) {
01251       /* Don't allow building over roads of other cities */
01252       if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN) && Town::GetByTile(tile) != t) {
01253         _grow_town_result = GROWTH_SUCCEED;
01254       } else if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_NONE) && _game_mode == GM_EDITOR) {
01255         /* If we are in the SE, and this road-piece has no town owner yet, it just found an
01256          * owner :) (happy happy happy road now) */
01257         SetRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN);
01258         SetTownIndex(tile, t->index);
01259       }
01260     }
01261 
01262     /* Max number of times is checked. */
01263   } while (--_grow_town_result >= 0);
01264 
01265   return (_grow_town_result == -2);
01266 }
01267 
01275 static RoadBits GenRandomRoadBits()
01276 {
01277   uint32 r = Random();
01278   uint a = GB(r, 0, 2);
01279   uint b = GB(r, 8, 2);
01280   if (a == b) b ^= 2;
01281   return (RoadBits)((ROAD_NW << a) + (ROAD_NW << b));
01282 }
01283 
01289 static bool GrowTown(Town *t)
01290 {
01291   static const TileIndexDiffC _town_coord_mod[] = {
01292     {-1,  0},
01293     { 1,  1},
01294     { 1, -1},
01295     {-1, -1},
01296     {-1,  0},
01297     { 0,  2},
01298     { 2,  0},
01299     { 0, -2},
01300     {-1, -1},
01301     {-2,  2},
01302     { 2,  2},
01303     { 2, -2},
01304     { 0,  0}
01305   };
01306 
01307   /* Current "company" is a town */
01308   Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
01309 
01310   TileIndex tile = t->xy; // The tile we are working with ATM
01311 
01312   /* Find a road that we can base the construction on. */
01313   const TileIndexDiffC *ptr;
01314   for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
01315     if (GetTownRoadBits(tile) != ROAD_NONE) {
01316       int r = GrowTownAtRoad(t, tile);
01317       cur_company.Restore();
01318       return r != 0;
01319     }
01320     tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
01321   }
01322 
01323   /* No road available, try to build a random road block by
01324    * clearing some land and then building a road there. */
01325   if (_settings_game.economy.allow_town_roads || _generating_world) {
01326     tile = t->xy;
01327     for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
01328       /* Only work with plain land that not already has a house */
01329       if (!IsTileType(tile, MP_HOUSE) && GetTileSlope(tile, NULL) == SLOPE_FLAT) {
01330         if (DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded()) {
01331           DoCommand(tile, GenRandomRoadBits(), t->index, DC_EXEC | DC_AUTO, CMD_BUILD_ROAD);
01332           cur_company.Restore();
01333           return true;
01334         }
01335       }
01336       tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
01337     }
01338   }
01339 
01340   cur_company.Restore();
01341   return false;
01342 }
01343 
01344 void UpdateTownRadius(Town *t)
01345 {
01346   static const uint32 _town_squared_town_zone_radius_data[23][5] = {
01347     {  4,  0,  0,  0,  0}, // 0
01348     { 16,  0,  0,  0,  0},
01349     { 25,  0,  0,  0,  0},
01350     { 36,  0,  0,  0,  0},
01351     { 49,  0,  4,  0,  0},
01352     { 64,  0,  4,  0,  0}, // 20
01353     { 64,  0,  9,  0,  1},
01354     { 64,  0,  9,  0,  4},
01355     { 64,  0, 16,  0,  4},
01356     { 81,  0, 16,  0,  4},
01357     { 81,  0, 16,  0,  4}, // 40
01358     { 81,  0, 25,  0,  9},
01359     { 81, 36, 25,  0,  9},
01360     { 81, 36, 25, 16,  9},
01361     { 81, 49,  0, 25,  9},
01362     { 81, 64,  0, 25,  9}, // 60
01363     { 81, 64,  0, 36,  9},
01364     { 81, 64,  0, 36, 16},
01365     {100, 81,  0, 49, 16},
01366     {100, 81,  0, 49, 25},
01367     {121, 81,  0, 49, 25}, // 80
01368     {121, 81,  0, 49, 25},
01369     {121, 81,  0, 49, 36}, // 88
01370   };
01371 
01372   if (t->num_houses < 92) {
01373     memcpy(t->squared_town_zone_radius, _town_squared_town_zone_radius_data[t->num_houses / 4], sizeof(t->squared_town_zone_radius));
01374   } else {
01375     int mass = t->num_houses / 8;
01376     /* Actually we are proportional to sqrt() but that's right because we are covering an area.
01377      * The offsets are to make sure the radii do not decrease in size when going from the table
01378      * to the calculated value.*/
01379     t->squared_town_zone_radius[0] = mass * 15 - 40;
01380     t->squared_town_zone_radius[1] = mass * 9 - 15;
01381     t->squared_town_zone_radius[2] = 0;
01382     t->squared_town_zone_radius[3] = mass * 5 - 5;
01383     t->squared_town_zone_radius[4] = mass * 3 + 5;
01384   }
01385 }
01386 
01387 void UpdateTownMaxPass(Town *t)
01388 {
01389   t->max_pass = t->population >> 3;
01390   t->max_mail = t->population >> 4;
01391 }
01392 
01404 static void DoCreateTown(Town *t, TileIndex tile, uint32 townnameparts, TownSize size, bool city, TownLayout layout, bool manual)
01405 {
01406   t->xy = tile;
01407   t->num_houses = 0;
01408   t->time_until_rebuild = 10;
01409   UpdateTownRadius(t);
01410   t->flags = 0;
01411   t->population = 0;
01412   t->grow_counter = 0;
01413   t->growth_rate = 250;
01414   t->new_max_pass = 0;
01415   t->new_max_mail = 0;
01416   t->new_act_pass = 0;
01417   t->new_act_mail = 0;
01418   t->max_pass = 0;
01419   t->max_mail = 0;
01420   t->act_pass = 0;
01421   t->act_mail = 0;
01422 
01423   t->pct_pass_transported = 0;
01424   t->pct_mail_transported = 0;
01425   t->fund_buildings_months = 0;
01426   t->new_act_food = 0;
01427   t->new_act_water = 0;
01428   t->act_food = 0;
01429   t->act_water = 0;
01430 
01431   for (uint i = 0; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
01432 
01433   t->have_ratings = 0;
01434   t->exclusivity = INVALID_COMPANY;
01435   t->exclusive_counter = 0;
01436   t->statues = 0;
01437 
01438   extern int _nb_orig_names;
01439   if (_settings_game.game_creation.town_name < _nb_orig_names) {
01440     /* Original town name */
01441     t->townnamegrfid = 0;
01442     t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
01443   } else {
01444     /* Newgrf town name */
01445     t->townnamegrfid = GetGRFTownNameId(_settings_game.game_creation.town_name  - _nb_orig_names);
01446     t->townnametype  = GetGRFTownNameType(_settings_game.game_creation.town_name - _nb_orig_names);
01447   }
01448   t->townnameparts = townnameparts;
01449 
01450   t->UpdateVirtCoord();
01451   InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
01452 
01453   t->InitializeLayout(layout);
01454 
01455   t->larger_town = city;
01456 
01457   int x = (int)size * 16 + 3;
01458   if (size == TSZ_RANDOM) x = (Random() & 0xF) + 8;
01459   /* Don't create huge cities when founding town in-game */
01460   if (city && (!manual || _game_mode == GM_EDITOR)) x *= _settings_game.economy.initial_city_size;
01461 
01462   t->num_houses += x;
01463   UpdateTownRadius(t);
01464 
01465   int i = x * 4;
01466   do {
01467     GrowTown(t);
01468   } while (--i);
01469 
01470   t->num_houses -= x;
01471   UpdateTownRadius(t);
01472   UpdateTownMaxPass(t);
01473   UpdateAirportsNoise();
01474 }
01475 
01481 static CommandCost TownCanBePlacedHere(TileIndex tile)
01482 {
01483   /* Check if too close to the edge of map */
01484   if (DistanceFromEdge(tile) < 12) {
01485     return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP_SUB);
01486   }
01487 
01488   /* Check distance to all other towns. */
01489   if (IsCloseToTown(tile, 20)) {
01490     return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_TOWN);
01491   }
01492 
01493   /* Can only build on clear flat areas, possibly with trees. */
01494   if ((!IsTileType(tile, MP_CLEAR) && !IsTileType(tile, MP_TREES)) || GetTileSlope(tile, NULL) != SLOPE_FLAT) {
01495     return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
01496   }
01497 
01498   return CommandCost(EXPENSES_OTHER);
01499 }
01500 
01506 static bool IsUniqueTownName(const char *name)
01507 {
01508   const Town *t;
01509 
01510   FOR_ALL_TOWNS(t) {
01511     if (t->name != NULL && strcmp(t->name, name) == 0) return false;
01512   }
01513 
01514   return true;
01515 }
01516 
01529 CommandCost CmdFoundTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01530 {
01531   TownSize size = Extract<TownSize, 0, 2>(p1);
01532   bool city = HasBit(p1, 2);
01533   TownLayout layout = Extract<TownLayout, 3, 3>(p1);
01534   TownNameParams par(_settings_game.game_creation.town_name);
01535   bool random = HasBit(p1, 6);
01536   uint32 townnameparts = p2;
01537 
01538   if (size >= TSZ_END) return CMD_ERROR;
01539   if (layout >= NUM_TLS) return CMD_ERROR;
01540 
01541   /* Some things are allowed only in the scenario editor */
01542   if (_game_mode != GM_EDITOR) {
01543     if (_settings_game.economy.found_town == TF_FORBIDDEN) return CMD_ERROR;
01544     if (size == TSZ_LARGE) return CMD_ERROR;
01545     if (random) return CMD_ERROR;
01546     if (_settings_game.economy.found_town != TF_CUSTOM_LAYOUT && layout != _settings_game.economy.town_layout) {
01547       return CMD_ERROR;
01548     }
01549   }
01550 
01551   if (StrEmpty(text)) {
01552     /* If supplied name is empty, townnameparts has to generate unique automatic name */
01553     if (!VerifyTownName(townnameparts, &par)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
01554   } else {
01555     /* If name is not empty, it has to be unique custom name */
01556     if (Utf8StringLength(text) >= MAX_LENGTH_TOWN_NAME_CHARS) return CMD_ERROR;
01557     if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
01558   }
01559 
01560   /* Allocate town struct */
01561   if (!Town::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_TOWNS);
01562 
01563   if (!random) {
01564     CommandCost ret = TownCanBePlacedHere(tile);
01565     if (ret.Failed()) return ret;
01566   }
01567 
01568   static const byte price_mult[][TSZ_RANDOM + 1] = {{ 15, 25, 40, 25 }, { 20, 35, 55, 35 }};
01569   /* multidimensional arrays have to have defined length of non-first dimension */
01570   assert_compile(lengthof(price_mult[0]) == 4);
01571 
01572   CommandCost cost(EXPENSES_OTHER, _price[PR_BUILD_TOWN]);
01573   byte mult = price_mult[city][size];
01574 
01575   cost.MultiplyCost(mult);
01576 
01577   /* Create the town */
01578   if (flags & DC_EXEC) {
01579     if (cost.GetCost() > GetAvailableMoneyForCommand()) {
01580       _additional_cash_required = cost.GetCost();
01581       return CommandCost(EXPENSES_OTHER);
01582     }
01583 
01584     _generating_world = true;
01585     UpdateNearestTownForRoadTiles(true);
01586     Town *t;
01587     if (random) {
01588       t = CreateRandomTown(20, townnameparts, size, city, layout);
01589       if (t == NULL) {
01590         cost = CommandCost(STR_ERROR_NO_SPACE_FOR_TOWN);
01591       } else {
01592         _new_town_id = t->index;
01593       }
01594     } else {
01595       t = new Town(tile);
01596       DoCreateTown(t, tile, townnameparts, size, city, layout, true);
01597     }
01598     UpdateNearestTownForRoadTiles(false);
01599     _generating_world = false;
01600 
01601     if (t != NULL && !StrEmpty(text)) {
01602       t->name = strdup(text);
01603       t->UpdateVirtCoord();
01604     }
01605 
01606     if (_game_mode != GM_EDITOR) {
01607       /* 't' can't be NULL since 'random' is false outside scenedit */
01608       assert(!random);
01609       char company_name[MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH];
01610       SetDParam(0, _current_company);
01611       GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
01612 
01613       char *cn = strdup(company_name);
01614       SetDParamStr(0, cn);
01615       SetDParam(1, t->index);
01616 
01617       AddNewsItem(STR_NEWS_NEW_TOWN, NS_INDUSTRY_OPEN, NR_TILE, tile, NR_NONE, UINT32_MAX, cn);
01618       AI::BroadcastNewEvent(new AIEventTownFounded(t->index));
01619     }
01620   }
01621   return cost;
01622 }
01623 
01633 static TileIndex AlignTileToGrid(TileIndex tile, TownLayout layout)
01634 {
01635   switch (layout) {
01636     case TL_2X2_GRID: return TileXY(TileX(tile) - TileX(tile) % 3, TileY(tile) - TileY(tile) % 3);
01637     case TL_3X3_GRID: return TileXY(TileX(tile) & ~3, TileY(tile) & ~3);
01638     default:          return tile;
01639   }
01640 }
01641 
01651 static bool IsTileAlignedToGrid(TileIndex tile, TownLayout layout)
01652 {
01653   switch (layout) {
01654     case TL_2X2_GRID: return TileX(tile) % 3 == 0 && TileY(tile) % 3 == 0;
01655     case TL_3X3_GRID: return TileX(tile) % 4 == 0 && TileY(tile) % 4 == 0;
01656     default:          return true;
01657   }
01658 }
01659 
01663 struct SpotData {
01664   TileIndex tile; 
01665   uint max_dist;  
01666   TownLayout layout; 
01667 };
01668 
01685 static bool FindFurthestFromWater(TileIndex tile, void *user_data)
01686 {
01687   SpotData *sp = (SpotData*)user_data;
01688   uint dist = GetClosestWaterDistance(tile, true);
01689 
01690   if (IsTileType(tile, MP_CLEAR) &&
01691       GetTileSlope(tile, NULL) == SLOPE_FLAT &&
01692       IsTileAlignedToGrid(tile, sp->layout) &&
01693       dist > sp->max_dist) {
01694     sp->tile = tile;
01695     sp->max_dist = dist;
01696   }
01697 
01698   return false;
01699 }
01700 
01707 static bool FindNearestEmptyLand(TileIndex tile, void *user_data)
01708 {
01709   return IsTileType(tile, MP_CLEAR);
01710 }
01711 
01724 static TileIndex FindNearestGoodCoastalTownSpot(TileIndex tile, TownLayout layout)
01725 {
01726   SpotData sp = { INVALID_TILE, 0, layout };
01727 
01728   TileIndex coast = tile;
01729   if (CircularTileSearch(&coast, 40, FindNearestEmptyLand, NULL)) {
01730     CircularTileSearch(&coast, 10, FindFurthestFromWater, &sp);
01731     return sp.tile;
01732   }
01733 
01734   /* if we get here just give up */
01735   return INVALID_TILE;
01736 }
01737 
01738 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout)
01739 {
01740   if (!Town::CanAllocateItem()) return NULL;
01741 
01742   do {
01743     /* Generate a tile index not too close from the edge */
01744     TileIndex tile = AlignTileToGrid(RandomTile(), layout);
01745 
01746     /* if we tried to place the town on water, slide it over onto
01747      * the nearest likely-looking spot */
01748     if (IsTileType(tile, MP_WATER)) {
01749       tile = FindNearestGoodCoastalTownSpot(tile, layout);
01750       if (tile == INVALID_TILE) continue;
01751     }
01752 
01753     /* Make sure town can be placed here */
01754     if (TownCanBePlacedHere(tile).Failed()) continue;
01755 
01756     /* Allocate a town struct */
01757     Town *t = new Town(tile);
01758 
01759     DoCreateTown(t, tile, townnameparts, size, city, layout, false);
01760 
01761     /* if the population is still 0 at the point, then the
01762      * placement is so bad it couldn't grow at all */
01763     if (t->population > 0) return t;
01764     DoCommand(t->xy, t->index, 0, DC_EXEC, CMD_DELETE_TOWN);
01765 
01766     /* We already know that we can allocate a single town when
01767      * entering this function. However, we create and delete
01768      * a town which "resets" the allocation checks. As such we
01769      * need to check again when assertions are enabled. */
01770     assert(Town::CanAllocateItem());
01771   } while (--attempts != 0);
01772 
01773   return NULL;
01774 }
01775 
01776 static const byte _num_initial_towns[4] = {5, 11, 23, 46};  // very low, low, normal, high
01777 
01785 bool GenerateTowns(TownLayout layout)
01786 {
01787   uint current_number = 0;
01788   uint difficulty = (_game_mode != GM_EDITOR) ? _settings_game.difficulty.number_towns : 0;
01789   uint total = (difficulty == (uint)CUSTOM_TOWN_NUMBER_DIFFICULTY) ? _settings_game.game_creation.custom_town_number : ScaleByMapSize(_num_initial_towns[difficulty] + (Random() & 7));
01790   uint32 townnameparts;
01791 
01792   SetGeneratingWorldProgress(GWP_TOWN, total);
01793 
01794   /* First attempt will be made at creating the suggested number of towns.
01795    * Note that this is really a suggested value, not a required one.
01796    * We would not like the system to lock up just because the user wanted 100 cities on a 64*64 map, would we? */
01797   do {
01798     bool city = (_settings_game.economy.larger_towns != 0 && Chance16(1, _settings_game.economy.larger_towns));
01799     IncreaseGeneratingWorldProgress(GWP_TOWN);
01800     /* Get a unique name for the town. */
01801     if (!GenerateTownName(&townnameparts)) continue;
01802     /* try 20 times to create a random-sized town for the first loop. */
01803     if (CreateRandomTown(20, townnameparts, TSZ_RANDOM, city, layout) != NULL) current_number++; // If creation was successful, raise a flag.
01804   } while (--total);
01805 
01806   if (current_number != 0) return true;
01807 
01808   /* If current_number is still zero at this point, it means that not a single town has been created.
01809    * So give it a last try, but now more aggressive */
01810   if (GenerateTownName(&townnameparts) &&
01811       CreateRandomTown(10000, townnameparts, TSZ_RANDOM, _settings_game.economy.larger_towns != 0, layout) != NULL) {
01812     return true;
01813   }
01814 
01815   /* If there are no towns at all and we are generating new game, bail out */
01816   if (Town::GetNumItems() == 0 && _game_mode != GM_EDITOR) {
01817     extern StringID _switch_mode_errorstr;
01818     _switch_mode_errorstr = STR_ERROR_COULD_NOT_CREATE_TOWN;
01819   }
01820 
01821   return false;  // we are still without a town? we failed, simply
01822 }
01823 
01824 
01831 HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
01832 {
01833   uint dist = DistanceSquare(tile, t->xy);
01834 
01835   if (t->fund_buildings_months && dist <= 25) return HZB_TOWN_CENTRE;
01836 
01837   HouseZonesBits smallest = HZB_TOWN_EDGE;
01838   for (HouseZonesBits i = HZB_BEGIN; i < HZB_END; i++) {
01839     if (dist < t->squared_town_zone_radius[i]) smallest = i;
01840   }
01841 
01842   return smallest;
01843 }
01844 
01855 static inline void ClearMakeHouseTile(TileIndex tile, Town *t, byte counter, byte stage, HouseID type, byte random_bits)
01856 {
01857   CommandCost cc = DoCommand(tile, 0, 0, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR);
01858 
01859   assert(cc.Succeeded());
01860 
01861   IncreaseBuildingCount(t, type);
01862   MakeHouseTile(tile, t->index, counter, stage, type, random_bits);
01863   if (HouseSpec::Get(type)->building_flags & BUILDING_IS_ANIMATED) AddAnimatedTile(tile);
01864 
01865   MarkTileDirtyByTile(tile);
01866 }
01867 
01868 
01879 static void MakeTownHouse(TileIndex t, Town *town, byte counter, byte stage, HouseID type, byte random_bits)
01880 {
01881   BuildingFlags size = HouseSpec::Get(type)->building_flags;
01882 
01883   ClearMakeHouseTile(t, town, counter, stage, type, random_bits);
01884   if (size & BUILDING_2_TILES_Y)   ClearMakeHouseTile(t + TileDiffXY(0, 1), town, counter, stage, ++type, random_bits);
01885   if (size & BUILDING_2_TILES_X)   ClearMakeHouseTile(t + TileDiffXY(1, 0), town, counter, stage, ++type, random_bits);
01886   if (size & BUILDING_HAS_4_TILES) ClearMakeHouseTile(t + TileDiffXY(1, 1), town, counter, stage, ++type, random_bits);
01887 }
01888 
01889 
01898 static inline bool CanBuildHouseHere(TileIndex tile, TownID town, bool noslope)
01899 {
01900   /* cannot build on these slopes... */
01901   Slope slope = GetTileSlope(tile, NULL);
01902   if ((noslope && slope != SLOPE_FLAT) || IsSteepSlope(slope)) return false;
01903 
01904   /* building under a bridge? */
01905   if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return false;
01906 
01907   /* do not try to build over house owned by another town */
01908   if (IsTileType(tile, MP_HOUSE) && GetTownIndex(tile) != town) return false;
01909 
01910   /* can we clear the land? */
01911   return DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded();
01912 }
01913 
01914 
01924 static inline bool CheckBuildHouseSameZ(TileIndex tile, TownID town, uint z, bool noslope)
01925 {
01926   if (!CanBuildHouseHere(tile, town, noslope)) return false;
01927 
01928   /* if building on slopes is allowed, there will be flattening foundation (to tile max z) */
01929   if (GetTileMaxZ(tile) != z) return false;
01930 
01931   return true;
01932 }
01933 
01934 
01944 static bool CheckFree2x2Area(TileIndex tile, TownID town, uint z, bool noslope)
01945 {
01946   /* we need to check this tile too because we can be at different tile now */
01947   if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
01948 
01949   for (DiagDirection d = DIAGDIR_SE; d < DIAGDIR_END; d++) {
01950     tile += TileOffsByDiagDir(d);
01951     if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
01952   }
01953 
01954   return true;
01955 }
01956 
01957 
01965 static inline bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile)
01966 {
01967   /* Allow towns everywhere when we don't build roads */
01968   if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
01969 
01970   TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
01971 
01972   switch (t->layout) {
01973     case TL_2X2_GRID:
01974       if ((grid_pos.x % 3) == 0 || (grid_pos.y % 3) == 0) return false;
01975       break;
01976 
01977     case TL_3X3_GRID:
01978       if ((grid_pos.x % 4) == 0 || (grid_pos.y % 4) == 0) return false;
01979       break;
01980 
01981     default:
01982       break;
01983   }
01984 
01985   return true;
01986 }
01987 
01988 
01996 static inline bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile)
01997 {
01998   /* Allow towns everywhere when we don't build roads */
01999   if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
02000 
02001   /* Compute relative position of tile. (Positive offsets are towards north) */
02002   TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
02003 
02004   switch (t->layout) {
02005     case TL_2X2_GRID:
02006       grid_pos.x %= 3;
02007       grid_pos.y %= 3;
02008       if ((grid_pos.x != 2 && grid_pos.x != -1) ||
02009         (grid_pos.y != 2 && grid_pos.y != -1)) return false;
02010       break;
02011 
02012     case TL_3X3_GRID:
02013       if ((grid_pos.x & 3) < 2 || (grid_pos.y & 3) < 2) return false;
02014       break;
02015 
02016     default:
02017       break;
02018   }
02019 
02020   return true;
02021 }
02022 
02023 
02033 static bool CheckTownBuild2House(TileIndex *tile, Town *t, uint maxz, bool noslope, DiagDirection second)
02034 {
02035   /* 'tile' is already checked in BuildTownHouse() - CanBuildHouseHere() and slope test */
02036 
02037   TileIndex tile2 = *tile + TileOffsByDiagDir(second);
02038   if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) return true;
02039 
02040   tile2 = *tile + TileOffsByDiagDir(ReverseDiagDir(second));
02041   if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) {
02042     *tile = tile2;
02043     return true;
02044   }
02045 
02046   return false;
02047 }
02048 
02049 
02058 static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, uint maxz, bool noslope)
02059 {
02060   TileIndex tile2 = *tile;
02061 
02062   for (DiagDirection d = DIAGDIR_SE;;d++) { // 'd' goes through DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_END
02063     if (TownLayoutAllows2x2HouseHere(t, tile2) && CheckFree2x2Area(tile2, t->index, maxz, noslope)) {
02064       *tile = tile2;
02065       return true;
02066     }
02067     if (d == DIAGDIR_END) break;
02068     tile2 += TileOffsByDiagDir(ReverseDiagDir(d)); // go clockwise
02069   }
02070 
02071   return false;
02072 }
02073 
02074 
02081 static bool BuildTownHouse(Town *t, TileIndex tile)
02082 {
02083   /* forbidden building here by town layout */
02084   if (!TownLayoutAllowsHouseHere(t, tile)) return false;
02085 
02086   /* no house allowed at all, bail out */
02087   if (!CanBuildHouseHere(tile, t->index, false)) return false;
02088 
02089   uint z;
02090   Slope slope = GetTileSlope(tile, &z);
02091 
02092   /* Get the town zone type of the current tile, as well as the climate.
02093    * This will allow to easily compare with the specs of the new house to build */
02094   HouseZonesBits rad = GetTownRadiusGroup(t, tile);
02095 
02096   /* Above snow? */
02097   int land = _settings_game.game_creation.landscape;
02098   if (land == LT_ARCTIC && z >= HighestSnowLine()) land = -1;
02099 
02100   uint bitmask = (1 << rad) + (1 << (land + 12));
02101 
02102   /* bits 0-4 are used
02103    * bits 11-15 are used
02104    * bits 5-10 are not used. */
02105   HouseID houses[HOUSE_MAX];
02106   uint num = 0;
02107   uint probs[HOUSE_MAX];
02108   uint probability_max = 0;
02109 
02110   /* Generate a list of all possible houses that can be built. */
02111   for (uint i = 0; i < HOUSE_MAX; i++) {
02112     const HouseSpec *hs = HouseSpec::Get(i);
02113 
02114     /* Verify that the candidate house spec matches the current tile status */
02115     if ((~hs->building_availability & bitmask) != 0 || !hs->enabled || hs->grf_prop.override != INVALID_HOUSE_ID) continue;
02116 
02117     /* Don't let these counters overflow. Global counters are 32bit, there will never be that many houses. */
02118     if (hs->class_id != HOUSE_NO_CLASS) {
02119       /* id_count is always <= class_count, so it doesn't need to be checked */
02120       if (t->building_counts.class_count[hs->class_id] == UINT16_MAX) continue;
02121     } else {
02122       /* If the house has no class, check id_count instead */
02123       if (t->building_counts.id_count[i] == UINT16_MAX) continue;
02124     }
02125 
02126     /* Without NewHouses, all houses have probability '1' */
02127     uint cur_prob = (_loaded_newgrf_features.has_newhouses ? hs->probability : 1);
02128     probability_max += cur_prob;
02129     probs[num] = cur_prob;
02130     houses[num++] = (HouseID)i;
02131   }
02132 
02133   uint maxz = GetTileMaxZ(tile);
02134   TileIndex baseTile = tile;
02135 
02136   while (probability_max > 0) {
02137     /* Building a multitile building can change the location of tile.
02138      * The building would still be built partially on that tile, but
02139      * its nothern tile would be elsewere. However, if the callback
02140      * fails we would be basing further work from the changed tile.
02141      * So a next 1x1 tile building could be built on the wrong tile. */
02142     tile = baseTile;
02143 
02144     uint r = RandomRange(probability_max);
02145     uint i;
02146     for (i = 0; i < num; i++) {
02147       if (probs[i] > r) break;
02148       r -= probs[i];
02149     }
02150 
02151     HouseID house = houses[i];
02152     probability_max -= probs[i];
02153 
02154     /* remove tested house from the set */
02155     num--;
02156     houses[i] = houses[num];
02157     probs[i] = probs[num];
02158 
02159     const HouseSpec *hs = HouseSpec::Get(house);
02160 
02161     if (_loaded_newgrf_features.has_newhouses && !_generating_world &&
02162         _game_mode != GM_EDITOR && (hs->extra_flags & BUILDING_IS_HISTORICAL) != 0) {
02163       continue;
02164     }
02165 
02166     if (_cur_year < hs->min_year || _cur_year > hs->max_year) continue;
02167 
02168     /* Special houses that there can be only one of. */
02169     uint oneof = 0;
02170 
02171     if (hs->building_flags & BUILDING_IS_CHURCH) {
02172       SetBit(oneof, TOWN_HAS_CHURCH);
02173     } else if (hs->building_flags & BUILDING_IS_STADIUM) {
02174       SetBit(oneof, TOWN_HAS_STADIUM);
02175     }
02176 
02177     if (t->flags & oneof) continue;
02178 
02179     /* Make sure there is no slope? */
02180     bool noslope = (hs->building_flags & TILE_NOT_SLOPED) != 0;
02181     if (noslope && slope != SLOPE_FLAT) continue;
02182 
02183     if (hs->building_flags & TILE_SIZE_2x2) {
02184       if (!CheckTownBuild2x2House(&tile, t, maxz, noslope)) continue;
02185     } else if (hs->building_flags & TILE_SIZE_2x1) {
02186       if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SW)) continue;
02187     } else if (hs->building_flags & TILE_SIZE_1x2) {
02188       if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SE)) continue;
02189     } else {
02190       /* 1x1 house checks are already done */
02191     }
02192 
02193     byte random_bits = Random();
02194 
02195     if (HasBit(hs->callback_mask, CBM_HOUSE_ALLOW_CONSTRUCTION)) {
02196       uint16 callback_res = GetHouseCallback(CBID_HOUSE_ALLOW_CONSTRUCTION, 0, 0, house, t, tile, true, random_bits);
02197       if (callback_res != CALLBACK_FAILED && GB(callback_res, 0, 8) == 0) continue;
02198     }
02199 
02200     /* build the house */
02201     t->num_houses++;
02202 
02203     /* Special houses that there can be only one of. */
02204     t->flags |= oneof;
02205 
02206     byte construction_counter = 0;
02207     byte construction_stage = 0;
02208 
02209     if (_generating_world || _game_mode == GM_EDITOR) {
02210       uint32 r = Random();
02211 
02212       construction_stage = TOWN_HOUSE_COMPLETED;
02213       if (Chance16(1, 7)) construction_stage = GB(r, 0, 2);
02214 
02215       if (construction_stage == TOWN_HOUSE_COMPLETED) {
02216         ChangePopulation(t, hs->population);
02217       } else {
02218         construction_counter = GB(r, 2, 2);
02219       }
02220     }
02221 
02222     MakeTownHouse(tile, t, construction_counter, construction_stage, house, random_bits);
02223 
02224     return true;
02225   }
02226 
02227   return false;
02228 }
02229 
02236 static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
02237 {
02238   assert(IsTileType(tile, MP_HOUSE));
02239   DecreaseBuildingCount(t, house);
02240   DoClearSquare(tile);
02241   DeleteAnimatedTile(tile);
02242 
02243   DeleteNewGRFInspectWindow(GSF_HOUSES, tile);
02244 }
02245 
02253 TileIndexDiff GetHouseNorthPart(HouseID &house)
02254 {
02255   if (house >= 3) { // house id 0,1,2 MUST be single tile houses, or this code breaks.
02256     if (HouseSpec::Get(house - 1)->building_flags & TILE_SIZE_2x1) {
02257       house--;
02258       return TileDiffXY(-1, 0);
02259     } else if (HouseSpec::Get(house - 1)->building_flags & BUILDING_2_TILES_Y) {
02260       house--;
02261       return TileDiffXY(0, -1);
02262     } else if (HouseSpec::Get(house - 2)->building_flags & BUILDING_HAS_4_TILES) {
02263       house -= 2;
02264       return TileDiffXY(-1, 0);
02265     } else if (HouseSpec::Get(house - 3)->building_flags & BUILDING_HAS_4_TILES) {
02266       house -= 3;
02267       return TileDiffXY(-1, -1);
02268     }
02269   }
02270   return 0;
02271 }
02272 
02273 void ClearTownHouse(Town *t, TileIndex tile)
02274 {
02275   assert(IsTileType(tile, MP_HOUSE));
02276 
02277   HouseID house = GetHouseType(tile);
02278 
02279   /* need to align the tile to point to the upper left corner of the house */
02280   tile += GetHouseNorthPart(house); // modifies house to the ID of the north tile
02281 
02282   const HouseSpec *hs = HouseSpec::Get(house);
02283 
02284   /* Remove population from the town if the house is finished. */
02285   if (IsHouseCompleted(tile)) {
02286     ChangePopulation(t, -hs->population);
02287   }
02288 
02289   t->num_houses--;
02290 
02291   /* Clear flags for houses that only may exist once/town. */
02292   if (hs->building_flags & BUILDING_IS_CHURCH) {
02293     ClrBit(t->flags, TOWN_HAS_CHURCH);
02294   } else if (hs->building_flags & BUILDING_IS_STADIUM) {
02295     ClrBit(t->flags, TOWN_HAS_STADIUM);
02296   }
02297 
02298   /* Do the actual clearing of tiles */
02299   uint eflags = hs->building_flags;
02300   DoClearTownHouseHelper(tile, t, house);
02301   if (eflags & BUILDING_2_TILES_Y)   DoClearTownHouseHelper(tile + TileDiffXY(0, 1), t, ++house);
02302   if (eflags & BUILDING_2_TILES_X)   DoClearTownHouseHelper(tile + TileDiffXY(1, 0), t, ++house);
02303   if (eflags & BUILDING_HAS_4_TILES) DoClearTownHouseHelper(tile + TileDiffXY(1, 1), t, ++house);
02304 }
02305 
02315 CommandCost CmdRenameTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02316 {
02317   Town *t = Town::GetIfValid(p1);
02318   if (t == NULL) return CMD_ERROR;
02319 
02320   bool reset = StrEmpty(text);
02321 
02322   if (!reset) {
02323     if (Utf8StringLength(text) >= MAX_LENGTH_TOWN_NAME_CHARS) return CMD_ERROR;
02324     if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
02325   }
02326 
02327   if (flags & DC_EXEC) {
02328     free(t->name);
02329     t->name = reset ? NULL : strdup(text);
02330 
02331     t->UpdateVirtCoord();
02332     InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
02333     UpdateAllStationVirtCoords();
02334   }
02335   return CommandCost();
02336 }
02337 
02347 CommandCost CmdExpandTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02348 {
02349   if (_game_mode != GM_EDITOR) return CMD_ERROR;
02350   Town *t = Town::GetIfValid(p1);
02351   if (t == NULL) return CMD_ERROR;
02352 
02353   if (flags & DC_EXEC) {
02354     /* The more houses, the faster we grow */
02355     uint amount = RandomRange(ClampToU16(t->num_houses / 10)) + 3;
02356     t->num_houses += amount;
02357     UpdateTownRadius(t);
02358 
02359     uint n = amount * 10;
02360     do GrowTown(t); while (--n);
02361 
02362     t->num_houses -= amount;
02363     UpdateTownRadius(t);
02364 
02365     UpdateTownMaxPass(t);
02366   }
02367 
02368   return CommandCost();
02369 }
02370 
02380 CommandCost CmdDeleteTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02381 {
02382   if (_game_mode != GM_EDITOR) return CMD_ERROR;
02383   Town *t = Town::GetIfValid(p1);
02384   if (t == NULL) return CMD_ERROR;
02385 
02386   /* Stations refer to towns. */
02387   const Station *st;
02388   FOR_ALL_STATIONS(st) {
02389     if (st->town == t) {
02390       /* Non-oil rig stations are always a problem. */
02391       if (!(st->facilities & FACIL_AIRPORT) || st->airport.type != AT_OILRIG) return CMD_ERROR;
02392       /* We can only automatically delete oil rigs *if* there's no vehicle on them. */
02393       CommandCost ret = DoCommand(st->airport.tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02394       if (ret.Failed()) return ret;
02395     }
02396   }
02397 
02398   /* Depots refer to towns. */
02399   const Depot *d;
02400   FOR_ALL_DEPOTS(d) {
02401     if (d->town == t) return CMD_ERROR;
02402   }
02403 
02404   /* Check all tiles for town ownership. */
02405   for (TileIndex tile = 0; tile < MapSize(); ++tile) {
02406     bool try_clear = false;
02407     switch (GetTileType(tile)) {
02408       case MP_ROAD:
02409         try_clear = HasTownOwnedRoad(tile) && GetTownIndex(tile) == t->index;
02410         break;
02411 
02412       case MP_TUNNELBRIDGE:
02413         try_clear = IsTileOwner(tile, OWNER_TOWN) && ClosestTownFromTile(tile, UINT_MAX) == t;
02414         break;
02415 
02416       case MP_HOUSE:
02417         try_clear = GetTownIndex(tile) == t->index;
02418         break;
02419 
02420       case MP_INDUSTRY:
02421         try_clear = Industry::GetByTile(tile)->town == t;
02422         break;
02423 
02424       case MP_OBJECT:
02425         if (Town::GetNumItems() == 1) {
02426           /* No towns will be left, remove it! */
02427           try_clear = true;
02428         } else {
02429           Object *o = Object::GetByTile(tile);
02430           if (o->town == t) {
02431             if (GetObjectType(tile) == OBJECT_STATUE) {
02432               /* Statue... always remove. */
02433               try_clear = true;
02434             } else {
02435               /* Tell to find a new town. */
02436               if (flags & DC_EXEC) o->town = NULL;
02437             }
02438           }
02439         }
02440         break;
02441 
02442       default:
02443         break;
02444     }
02445     if (try_clear) {
02446       CommandCost ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02447       if (ret.Failed()) return ret;
02448     }
02449   }
02450 
02451   /* The town destructor will delete the other things related to the town. */
02452   if (flags & DC_EXEC) delete t;
02453 
02454   return CommandCost();
02455 }
02456 
02461 const byte _town_action_costs[TACT_COUNT] = {
02462   2, 4, 9, 35, 48, 53, 117, 175
02463 };
02464 
02465 static CommandCost TownActionAdvertiseSmall(Town *t, DoCommandFlag flags)
02466 {
02467   if (flags & DC_EXEC) {
02468     ModifyStationRatingAround(t->xy, _current_company, 0x40, 10);
02469   }
02470   return CommandCost();
02471 }
02472 
02473 static CommandCost TownActionAdvertiseMedium(Town *t, DoCommandFlag flags)
02474 {
02475   if (flags & DC_EXEC) {
02476     ModifyStationRatingAround(t->xy, _current_company, 0x70, 15);
02477   }
02478   return CommandCost();
02479 }
02480 
02481 static CommandCost TownActionAdvertiseLarge(Town *t, DoCommandFlag flags)
02482 {
02483   if (flags & DC_EXEC) {
02484     ModifyStationRatingAround(t->xy, _current_company, 0xA0, 20);
02485   }
02486   return CommandCost();
02487 }
02488 
02489 static CommandCost TownActionRoadRebuild(Town *t, DoCommandFlag flags)
02490 {
02491   /* Check if the company is allowed to fund new roads. */
02492   if (!_settings_game.economy.fund_roads) return CMD_ERROR;
02493 
02494   if (flags & DC_EXEC) {
02495     t->road_build_months = 6;
02496 
02497     char company_name[MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH];
02498     SetDParam(0, _current_company);
02499     GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
02500 
02501     char *cn = strdup(company_name);
02502     SetDParam(0, t->index);
02503     SetDParamStr(1, cn);
02504 
02505     AddNewsItem(STR_NEWS_ROAD_REBUILDING, NS_GENERAL, NR_TOWN, t->index, NR_NONE, UINT32_MAX, cn);
02506   }
02507   return CommandCost();
02508 }
02509 
02516 static bool SearchTileForStatue(TileIndex tile, void *user_data)
02517 {
02518   /* Statues can be build on slopes, just like houses. Only the steep slopes is a no go. */
02519   if (IsSteepSlope(GetTileSlope(tile, NULL))) return false;
02520   /* Don't build statues under bridges. */
02521   if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return false;
02522 
02523   if (!IsTileType(tile, MP_HOUSE) &&
02524       !IsTileType(tile, MP_CLEAR) &&
02525       !IsTileType(tile, MP_TREES)) {
02526     return false;
02527   }
02528 
02529   Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
02530   CommandCost r = DoCommand(tile, 0, 0, DC_NONE, CMD_LANDSCAPE_CLEAR);
02531   cur_company.Restore();
02532 
02533   if (r.Failed()) return false;
02534 
02535   return true;
02536 }
02537 
02545 static CommandCost TownActionBuildStatue(Town *t, DoCommandFlag flags)
02546 {
02547   if (!Object::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_OBJECTS);
02548 
02549   TileIndex tile = t->xy;
02550   if (CircularTileSearch(&tile, 9, SearchTileForStatue, NULL)) {
02551     if (flags & DC_EXEC) {
02552       Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
02553       DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
02554       cur_company.Restore();
02555       BuildObject(OBJECT_STATUE, tile, _current_company, t);
02556       SetBit(t->statues, _current_company); // Once found and built, "inform" the Town.
02557       MarkTileDirtyByTile(tile);
02558     }
02559     return CommandCost();
02560   }
02561   return_cmd_error(STR_ERROR_STATUE_NO_SUITABLE_PLACE);
02562 }
02563 
02564 static CommandCost TownActionFundBuildings(Town *t, DoCommandFlag flags)
02565 {
02566   if (flags & DC_EXEC) {
02567     /* Build next tick */
02568     t->grow_counter = 1;
02569     /* If we were not already growing */
02570     SetBit(t->flags, TOWN_IS_FUNDED);
02571     /* And grow for 3 months */
02572     t->fund_buildings_months = 3;
02573   }
02574   return CommandCost();
02575 }
02576 
02577 static CommandCost TownActionBuyRights(Town *t, DoCommandFlag flags)
02578 {
02579   /* Check if it's allowed to buy the rights */
02580   if (!_settings_game.economy.exclusive_rights) return CMD_ERROR;
02581 
02582   if (flags & DC_EXEC) {
02583     t->exclusive_counter = 12;
02584     t->exclusivity = _current_company;
02585 
02586     ModifyStationRatingAround(t->xy, _current_company, 130, 17);
02587   }
02588   return CommandCost();
02589 }
02590 
02591 static CommandCost TownActionBribe(Town *t, DoCommandFlag flags)
02592 {
02593   if (flags & DC_EXEC) {
02594     if (Chance16(1, 14)) {
02595       /* set as unwanted for 6 months */
02596       t->unwanted[_current_company] = 6;
02597 
02598       /* set all close by station ratings to 0 */
02599       Station *st;
02600       FOR_ALL_STATIONS(st) {
02601         if (st->town == t && st->owner == _current_company) {
02602           for (CargoID i = 0; i < NUM_CARGO; i++) st->goods[i].rating = 0;
02603         }
02604       }
02605 
02606       /* only show errormessage to the executing player. All errors are handled command.c
02607        * but this is special, because it can only 'fail' on a DC_EXEC */
02608       if (IsLocalCompany()) ShowErrorMessage(STR_ERROR_BRIBE_FAILED, STR_ERROR_BRIBE_FAILED_2, WL_INFO);
02609 
02610       /* decrease by a lot!
02611        * ChangeTownRating is only for stuff in demolishing. Bribe failure should
02612        * be independent of any cheat settings
02613        */
02614       if (t->ratings[_current_company] > RATING_BRIBE_DOWN_TO) {
02615         t->ratings[_current_company] = RATING_BRIBE_DOWN_TO;
02616         SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
02617       }
02618     } else {
02619       ChangeTownRating(t, RATING_BRIBE_UP_STEP, RATING_BRIBE_MAXIMUM, DC_EXEC);
02620     }
02621   }
02622   return CommandCost();
02623 }
02624 
02625 typedef CommandCost TownActionProc(Town *t, DoCommandFlag flags);
02626 static TownActionProc * const _town_action_proc[] = {
02627   TownActionAdvertiseSmall,
02628   TownActionAdvertiseMedium,
02629   TownActionAdvertiseLarge,
02630   TownActionRoadRebuild,
02631   TownActionBuildStatue,
02632   TownActionFundBuildings,
02633   TownActionBuyRights,
02634   TownActionBribe
02635 };
02636 
02644 uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t)
02645 {
02646   int num = 0;
02647   TownActions buttons = TACT_NONE;
02648 
02649   /* Spectators and unwanted have no options */
02650   if (cid != COMPANY_SPECTATOR && !(_settings_game.economy.bribe && t->unwanted[cid])) {
02651 
02652     /* Things worth more than this are not shown */
02653     Money avail = Company::Get(cid)->money + _price[PR_STATION_VALUE] * 200;
02654 
02655     /* Check the action bits for validity and
02656      * if they are valid add them */
02657     for (uint i = 0; i != lengthof(_town_action_costs); i++) {
02658       const TownActions cur = (TownActions)(1 << i);
02659 
02660       /* Is the company not able to bribe ? */
02661       if (cur == TACT_BRIBE && (!_settings_game.economy.bribe || t->ratings[cid] >= RATING_BRIBE_MAXIMUM)) continue;
02662 
02663       /* Is the company not able to buy exclusive rights ? */
02664       if (cur == TACT_BUY_RIGHTS && !_settings_game.economy.exclusive_rights) continue;
02665 
02666       /* Is the company not able to fund local road reconstruction? */
02667       if (cur == TACT_ROAD_REBUILD && !_settings_game.economy.fund_roads) continue;
02668 
02669       /* Is the company not able to build a statue ? */
02670       if (cur == TACT_BUILD_STATUE && HasBit(t->statues, cid)) continue;
02671 
02672       if (avail >= _town_action_costs[i] * _price[PR_TOWN_ACTION] >> 8) {
02673         buttons |= cur;
02674         num++;
02675       }
02676     }
02677   }
02678 
02679   if (nump != NULL) *nump = num;
02680   return buttons;
02681 }
02682 
02694 CommandCost CmdDoTownAction(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02695 {
02696   Town *t = Town::GetIfValid(p1);
02697   if (t == NULL || p2 >= lengthof(_town_action_proc)) return CMD_ERROR;
02698 
02699   if (!HasBit(GetMaskOfTownActions(NULL, _current_company, t), p2)) return CMD_ERROR;
02700 
02701   CommandCost cost(EXPENSES_OTHER, _price[PR_TOWN_ACTION] * _town_action_costs[p2] >> 8);
02702 
02703   CommandCost ret = _town_action_proc[p2](t, flags);
02704   if (ret.Failed()) return ret;
02705 
02706   if (flags & DC_EXEC) {
02707     SetWindowDirty(WC_TOWN_AUTHORITY, p1);
02708   }
02709 
02710   return cost;
02711 }
02712 
02713 static void UpdateTownGrowRate(Town *t)
02714 {
02715   /* Increase company ratings if they're low */
02716   const Company *c;
02717   FOR_ALL_COMPANIES(c) {
02718     if (t->ratings[c->index] < RATING_GROWTH_MAXIMUM) {
02719       t->ratings[c->index] = min((int)RATING_GROWTH_MAXIMUM, t->ratings[c->index] + RATING_GROWTH_UP_STEP);
02720     }
02721   }
02722 
02723   int n = 0;
02724 
02725   const Station *st;
02726   FOR_ALL_STATIONS(st) {
02727     if (DistanceSquare(st->xy, t->xy) <= t->squared_town_zone_radius[0]) {
02728       if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
02729         n++;
02730         if (Company::IsValidID(st->owner)) {
02731           int new_rating = t->ratings[st->owner] + RATING_STATION_UP_STEP;
02732           t->ratings[st->owner] = min(new_rating, INT16_MAX); // do not let it overflow
02733         }
02734       } else {
02735         if (Company::IsValidID(st->owner)) {
02736           int new_rating = t->ratings[st->owner] + RATING_STATION_DOWN_STEP;
02737           t->ratings[st->owner] = max(new_rating, INT16_MIN);
02738         }
02739       }
02740     }
02741   }
02742 
02743   /* clamp all ratings to valid values */
02744   for (uint i = 0; i < MAX_COMPANIES; i++) {
02745     t->ratings[i] = Clamp(t->ratings[i], RATING_MINIMUM, RATING_MAXIMUM);
02746   }
02747 
02748   SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
02749 
02750   ClrBit(t->flags, TOWN_IS_FUNDED);
02751   if (_settings_game.economy.town_growth_rate == 0 && t->fund_buildings_months == 0) return;
02752 
02757   static const uint16 _grow_count_values[2][6] = {
02758     { 120, 120, 120, 100,  80,  60 }, // Fund new buildings has been activated
02759     { 320, 420, 300, 220, 160, 100 }  // Normal values
02760   };
02761 
02762   uint16 m;
02763 
02764   if (t->fund_buildings_months != 0) {
02765     m = _grow_count_values[0][min(n, 5)];
02766     t->fund_buildings_months--;
02767   } else {
02768     m = _grow_count_values[1][min(n, 5)];
02769     if (n == 0 && !Chance16(1, 12)) return;
02770   }
02771 
02772   if (_settings_game.game_creation.landscape == LT_ARCTIC) {
02773     if (TilePixelHeight(t->xy) >= GetSnowLine() && t->act_food == 0 && t->population > 90) return;
02774 
02775   } else if (_settings_game.game_creation.landscape == LT_TROPIC) {
02776     if (GetTropicZone(t->xy) == TROPICZONE_DESERT && (t->act_food == 0 || t->act_water == 0) && t->population > 60) return;
02777   }
02778 
02779   /* Use the normal growth rate values if new buildings have been funded in
02780    * this town and the growth rate is set to none. */
02781   uint growth_multiplier = _settings_game.economy.town_growth_rate != 0 ? _settings_game.economy.town_growth_rate - 1 : 1;
02782 
02783   m >>= growth_multiplier;
02784   if (t->larger_town) m /= 2;
02785 
02786   t->growth_rate = m / (t->num_houses / 50 + 1);
02787   if (m <= t->grow_counter) {
02788     t->grow_counter = m;
02789   }
02790 
02791   SetBit(t->flags, TOWN_IS_FUNDED);
02792 }
02793 
02794 static void UpdateTownAmounts(Town *t)
02795 {
02796   /* Using +1 here to prevent overflow and division by zero */
02797   t->pct_pass_transported = t->new_act_pass * 256 / (t->new_max_pass + 1);
02798 
02799   t->max_pass = t->new_max_pass; t->new_max_pass = 0;
02800   t->act_pass = t->new_act_pass; t->new_act_pass = 0;
02801   t->act_food = t->new_act_food; t->new_act_food = 0;
02802   t->act_water = t->new_act_water; t->new_act_water = 0;
02803 
02804   /* Using +1 here to prevent overflow and division by zero */
02805   t->pct_mail_transported = t->new_act_mail * 256 / (t->new_max_mail + 1);
02806   t->max_mail = t->new_max_mail; t->new_max_mail = 0;
02807   t->act_mail = t->new_act_mail; t->new_act_mail = 0;
02808 
02809   SetWindowDirty(WC_TOWN_VIEW, t->index);
02810 }
02811 
02812 static void UpdateTownUnwanted(Town *t)
02813 {
02814   const Company *c;
02815 
02816   FOR_ALL_COMPANIES(c) {
02817     if (t->unwanted[c->index] > 0) t->unwanted[c->index]--;
02818   }
02819 }
02820 
02827 CommandCost CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags)
02828 {
02829   if (!Company::IsValidID(_current_company) || (flags & DC_NO_TEST_TOWN_RATING)) return CommandCost();
02830 
02831   Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
02832   if (t == NULL) return CommandCost();
02833 
02834   if (t->ratings[_current_company] > RATING_VERYPOOR) return CommandCost();
02835 
02836   SetDParam(0, t->index);
02837   return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
02838 }
02839 
02848 Town *CalcClosestTownFromTile(TileIndex tile, uint threshold)
02849 {
02850   Town *t;
02851   uint best = threshold;
02852   Town *best_town = NULL;
02853 
02854   FOR_ALL_TOWNS(t) {
02855     uint dist = DistanceManhattan(tile, t->xy);
02856     if (dist < best) {
02857       best = dist;
02858       best_town = t;
02859     }
02860   }
02861 
02862   return best_town;
02863 }
02864 
02873 Town *ClosestTownFromTile(TileIndex tile, uint threshold)
02874 {
02875   switch (GetTileType(tile)) {
02876     case MP_ROAD:
02877       if (IsRoadDepot(tile)) return CalcClosestTownFromTile(tile, threshold);
02878 
02879       if (!HasTownOwnedRoad(tile)) {
02880         TownID tid = GetTownIndex(tile);
02881 
02882         if (tid == (TownID)INVALID_TOWN) {
02883           /* in the case we are generating "many random towns", this value may be INVALID_TOWN */
02884           if (_generating_world) return CalcClosestTownFromTile(tile, threshold);
02885           assert(Town::GetNumItems() == 0);
02886           return NULL;
02887         }
02888 
02889         assert(Town::IsValidID(tid));
02890         Town *town = Town::Get(tid);
02891 
02892         if (DistanceManhattan(tile, town->xy) >= threshold) town = NULL;
02893 
02894         return town;
02895       }
02896       /* FALL THROUGH */
02897 
02898     case MP_HOUSE:
02899       return Town::GetByTile(tile);
02900 
02901     default:
02902       return CalcClosestTownFromTile(tile, threshold);
02903   }
02904 }
02905 
02906 static bool _town_rating_test = false; 
02907 static SmallMap<const Town *, int, 4> _town_test_ratings; 
02908 
02914 void SetTownRatingTestMode(bool mode)
02915 {
02916   static int ref_count = 0; // Number of times test-mode is switched on.
02917   if (mode) {
02918     if (ref_count == 0) {
02919       _town_test_ratings.Clear();
02920     }
02921     ref_count++;
02922   } else {
02923     assert(ref_count > 0);
02924     ref_count--;
02925   }
02926   _town_rating_test = !(ref_count == 0);
02927 }
02928 
02934 static int GetRating(const Town *t)
02935 {
02936   if (_town_rating_test) {
02937     SmallMap<const Town *, int>::iterator it = _town_test_ratings.Find(t);
02938     if (it != _town_test_ratings.End()) {
02939       return it->second;
02940     }
02941   }
02942   return t->ratings[_current_company];
02943 }
02944 
02952 void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
02953 {
02954   /* if magic_bulldozer cheat is active, town doesn't penalize for removing stuff */
02955   if (t == NULL || (flags & DC_NO_MODIFY_TOWN_RATING) ||
02956       !Company::IsValidID(_current_company) ||
02957       (_cheats.magic_bulldozer.value && add < 0)) {
02958     return;
02959   }
02960 
02961   int rating = GetRating(t);
02962   if (add < 0) {
02963     if (rating > max) {
02964       rating += add;
02965       if (rating < max) rating = max;
02966     }
02967   } else {
02968     if (rating < max) {
02969       rating += add;
02970       if (rating > max) rating = max;
02971     }
02972   }
02973   if (_town_rating_test) {
02974     _town_test_ratings[t] = rating;
02975   } else {
02976     SetBit(t->have_ratings, _current_company);
02977     t->ratings[_current_company] = rating;
02978     SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
02979   }
02980 }
02981 
02989 CommandCost CheckforTownRating(DoCommandFlag flags, Town *t, TownRatingCheckType type)
02990 {
02991   /* if magic_bulldozer cheat is active, town doesn't restrict your destructive actions */
02992   if (t == NULL || !Company::IsValidID(_current_company) ||
02993       _cheats.magic_bulldozer.value || (flags & DC_NO_TEST_TOWN_RATING)) {
02994     return CommandCost();
02995   }
02996 
02997   /* minimum rating needed to be allowed to remove stuff */
02998   static const int needed_rating[][TOWN_RATING_CHECK_TYPE_COUNT] = {
02999     /*                  ROAD_REMOVE,                    TUNNELBRIDGE_REMOVE */
03000     { RATING_ROAD_NEEDED_PERMISSIVE, RATING_TUNNEL_BRIDGE_NEEDED_PERMISSIVE}, // Permissive
03001     {    RATING_ROAD_NEEDED_NEUTRAL,    RATING_TUNNEL_BRIDGE_NEEDED_NEUTRAL}, // Neutral
03002     {    RATING_ROAD_NEEDED_HOSTILE,    RATING_TUNNEL_BRIDGE_NEEDED_HOSTILE}, // Hostile
03003   };
03004 
03005   /* check if you're allowed to remove the road/bridge/tunnel
03006    * owned by a town no removal if rating is lower than ... depends now on
03007    * difficulty setting. Minimum town rating selected by difficulty level
03008    */
03009   int needed = needed_rating[_settings_game.difficulty.town_council_tolerance][type];
03010 
03011   if (GetRating(t) < needed) {
03012     SetDParam(0, t->index);
03013     return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
03014   }
03015 
03016   return CommandCost();
03017 }
03018 
03019 void TownsMonthlyLoop()
03020 {
03021   Town *t;
03022 
03023   FOR_ALL_TOWNS(t) {
03024     if (t->road_build_months != 0) t->road_build_months--;
03025 
03026     if (t->exclusive_counter != 0) {
03027       if (--t->exclusive_counter == 0) t->exclusivity = INVALID_COMPANY;
03028     }
03029 
03030     UpdateTownGrowRate(t);
03031     UpdateTownAmounts(t);
03032     UpdateTownUnwanted(t);
03033   }
03034 }
03035 
03036 void TownsYearlyLoop()
03037 {
03038   /* Increment house ages */
03039   for (TileIndex t = 0; t < MapSize(); t++) {
03040     if (!IsTileType(t, MP_HOUSE)) continue;
03041     IncrementHouseAge(t);
03042   }
03043 }
03044 
03045 void InitializeTowns()
03046 {
03047   _town_pool.CleanPool();
03048 }
03049 
03050 static CommandCost TerraformTile_Town(TileIndex tile, DoCommandFlag flags, uint z_new, Slope tileh_new)
03051 {
03052   if (AutoslopeEnabled()) {
03053     HouseID house = GetHouseType(tile);
03054     GetHouseNorthPart(house); // modifies house to the ID of the north tile
03055     const HouseSpec *hs = HouseSpec::Get(house);
03056 
03057     /* Here we differ from TTDP by checking TILE_NOT_SLOPED */
03058     if (((hs->building_flags & TILE_NOT_SLOPED) == 0) && !IsSteepSlope(tileh_new) &&
03059         (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
03060       bool allow_terraform = true;
03061 
03062       /* Call the autosloping callback per tile, not for the whole building at once. */
03063       house = GetHouseType(tile);
03064       hs = HouseSpec::Get(house);
03065       if (HasBit(hs->callback_mask, CBM_HOUSE_AUTOSLOPE)) {
03066         /* If the callback fails, allow autoslope. */
03067         uint16 res = GetHouseCallback(CBID_HOUSE_AUTOSLOPE, 0, 0, house, Town::GetByTile(tile), tile);
03068         if ((res != 0) && (res != CALLBACK_FAILED)) allow_terraform = false;
03069       }
03070 
03071       if (allow_terraform) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
03072     }
03073   }
03074 
03075   return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
03076 }
03077 
03079 extern const TileTypeProcs _tile_type_town_procs = {
03080   DrawTile_Town,           // draw_tile_proc
03081   GetSlopeZ_Town,          // get_slope_z_proc
03082   ClearTile_Town,          // clear_tile_proc
03083   AddAcceptedCargo_Town,   // add_accepted_cargo_proc
03084   GetTileDesc_Town,        // get_tile_desc_proc
03085   GetTileTrackStatus_Town, // get_tile_track_status_proc
03086   NULL,                    // click_tile_proc
03087   AnimateTile_Town,        // animate_tile_proc
03088   TileLoop_Town,           // tile_loop_clear
03089   ChangeTileOwner_Town,    // change_tile_owner_clear
03090   AddProducedCargo_Town,   // add_produced_cargo_proc
03091   NULL,                    // vehicle_enter_tile_proc
03092   GetFoundation_Town,      // get_foundation_proc
03093   TerraformTile_Town,      // terraform_tile_proc
03094 };
03095 
03096 
03097 HouseSpec _house_specs[HOUSE_MAX];
03098 
03099 void ResetHouses()
03100 {
03101   memset(&_house_specs, 0, sizeof(_house_specs));
03102   memcpy(&_house_specs, &_original_house_specs, sizeof(_original_house_specs));
03103 
03104   /* Reset any overrides that have been set. */
03105   _house_mngr.ResetOverride();
03106 }