town_cmd.cpp

Go to the documentation of this file.
00001 /* $Id$ */
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 "error.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 "autoslope.h"
00030 #include "tunnelbridge_map.h"
00031 #include "strings_func.h"
00032 #include "window_func.h"
00033 #include "string_func.h"
00034 #include "newgrf_cargo.h"
00035 #include "cheat_type.h"
00036 #include "animated_tile_func.h"
00037 #include "date_func.h"
00038 #include "subsidy_func.h"
00039 #include "core/pool_func.hpp"
00040 #include "town.h"
00041 #include "townname_func.h"
00042 #include "core/random_func.hpp"
00043 #include "core/backup_type.hpp"
00044 #include "depot_base.h"
00045 #include "object_map.h"
00046 #include "object_base.h"
00047 #include "ai/ai.hpp"
00048 #include "game/game.hpp"
00049 
00050 #include "table/strings.h"
00051 #include "table/town_land.h"
00052 
00053 TownID _new_town_id;
00054 uint32 _town_cargoes_accepted; 
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   free(this->text);
00064 
00065   if (CleaningPool()) return;
00066 
00067   /* Delete town authority window
00068    * and remove from list of sorted towns */
00069   DeleteWindowById(WC_TOWN_VIEW, this->index);
00070 
00071   /* Check no industry is related to us. */
00072   const Industry *i;
00073   FOR_ALL_INDUSTRIES(i) assert(i->town != this);
00074 
00075   /* ... and no object is related to us. */
00076   const Object *o;
00077   FOR_ALL_OBJECTS(o) assert(o->town != this);
00078 
00079   /* Check no tile is related to us. */
00080   for (TileIndex tile = 0; tile < MapSize(); ++tile) {
00081     switch (GetTileType(tile)) {
00082       case MP_HOUSE:
00083         assert(GetTownIndex(tile) != this->index);
00084         break;
00085 
00086       case MP_ROAD:
00087         assert(!HasTownOwnedRoad(tile) || GetTownIndex(tile) != this->index);
00088         break;
00089 
00090       case MP_TUNNELBRIDGE:
00091         assert(!IsTileOwner(tile, OWNER_TOWN) || ClosestTownFromTile(tile, UINT_MAX) != this);
00092         break;
00093 
00094       default:
00095         break;
00096     }
00097   }
00098 
00099   /* Clear the persistent storage list. */
00100   this->psa_list.clear();
00101 
00102   DeleteSubsidyWith(ST_TOWN, this->index);
00103   DeleteNewGRFInspectWindow(GSF_FAKE_TOWNS, this->index);
00104   CargoPacket::InvalidateAllFrom(ST_TOWN, this->index);
00105   MarkWholeScreenDirty();
00106 }
00107 
00108 
00114 void Town::PostDestructor(size_t index)
00115 {
00116   InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
00117   UpdateNearestTownForRoadTiles(false);
00118 
00119   /* Give objects a new home! */
00120   Object *o;
00121   FOR_ALL_OBJECTS(o) {
00122     if (o->town == NULL) o->town = CalcClosestTownFromTile(o->location.tile, UINT_MAX);
00123   }
00124 }
00125 
00129 void Town::InitializeLayout(TownLayout layout)
00130 {
00131   if (layout != TL_RANDOM) {
00132     this->layout = layout;
00133     return;
00134   }
00135 
00136   this->layout = TileHash(TileX(this->xy), TileY(this->xy)) % (NUM_TLS - 1);
00137 }
00138 
00143 /* static */ Town *Town::GetRandom()
00144 {
00145   if (Town::GetNumItems() == 0) return NULL;
00146   int num = RandomRange((uint16)Town::GetNumItems());
00147   size_t index = MAX_UVALUE(size_t);
00148 
00149   while (num >= 0) {
00150     num--;
00151     index++;
00152 
00153     /* Make sure we have a valid town */
00154     while (!Town::IsValidID(index)) {
00155       index++;
00156       assert(index < Town::GetPoolSize());
00157     }
00158   }
00159 
00160   return Town::Get(index);
00161 }
00162 
00167 Money HouseSpec::GetRemovalCost() const
00168 {
00169   return (_price[PR_CLEAR_HOUSE] * this->removal_cost) >> 8;
00170 }
00171 
00172 // Local
00173 static int _grow_town_result;
00174 
00175 /* Describe the possible states */
00176 enum TownGrowthResult {
00177   GROWTH_SUCCEED         = -1,
00178   GROWTH_SEARCH_STOPPED  =  0
00179 //  GROWTH_SEARCH_RUNNING >=  1
00180 };
00181 
00182 static bool BuildTownHouse(Town *t, TileIndex tile);
00183 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout);
00184 
00185 static void TownDrawHouseLift(const TileInfo *ti)
00186 {
00187   AddChildSpriteScreen(SPR_LIFT, PAL_NONE, 14, 60 - GetLiftPosition(ti->tile));
00188 }
00189 
00190 typedef void TownDrawTileProc(const TileInfo *ti);
00191 static TownDrawTileProc * const _town_draw_tile_procs[1] = {
00192   TownDrawHouseLift
00193 };
00194 
00200 static inline DiagDirection RandomDiagDir()
00201 {
00202   return (DiagDirection)(3 & Random());
00203 }
00204 
00210 static void DrawTile_Town(TileInfo *ti)
00211 {
00212   HouseID house_id = GetHouseType(ti->tile);
00213 
00214   if (house_id >= NEW_HOUSE_OFFSET) {
00215     /* Houses don't necessarily need new graphics. If they don't have a
00216      * spritegroup associated with them, then the sprite for the substitute
00217      * house id is drawn instead. */
00218     if (HouseSpec::Get(house_id)->grf_prop.spritegroup[0] != NULL) {
00219       DrawNewHouseTile(ti, house_id);
00220       return;
00221     } else {
00222       house_id = HouseSpec::Get(house_id)->grf_prop.subst_id;
00223     }
00224   }
00225 
00226   /* Retrieve pointer to the draw town tile struct */
00227   const DrawBuildingsTileStruct *dcts = &_town_draw_tile_data[house_id << 4 | TileHash2Bit(ti->x, ti->y) << 2 | GetHouseBuildingStage(ti->tile)];
00228 
00229   if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
00230 
00231   DrawGroundSprite(dcts->ground.sprite, dcts->ground.pal);
00232 
00233   /* If houses are invisible, do not draw the upper part */
00234   if (IsInvisibilitySet(TO_HOUSES)) return;
00235 
00236   /* Add a house on top of the ground? */
00237   SpriteID image = dcts->building.sprite;
00238   if (image != 0) {
00239     AddSortableSpriteToDraw(image, dcts->building.pal,
00240       ti->x + dcts->subtile_x,
00241       ti->y + dcts->subtile_y,
00242       dcts->width,
00243       dcts->height,
00244       dcts->dz,
00245       ti->z,
00246       IsTransparencySet(TO_HOUSES)
00247     );
00248 
00249     if (IsTransparencySet(TO_HOUSES)) return;
00250   }
00251 
00252   {
00253     int proc = dcts->draw_proc - 1;
00254 
00255     if (proc >= 0) _town_draw_tile_procs[proc](ti);
00256   }
00257 }
00258 
00259 static int GetSlopePixelZ_Town(TileIndex tile, uint x, uint y)
00260 {
00261   return GetTileMaxPixelZ(tile);
00262 }
00263 
00265 static Foundation GetFoundation_Town(TileIndex tile, Slope tileh)
00266 {
00267   HouseID hid = GetHouseType(tile);
00268 
00269   /* For NewGRF house tiles we might not be drawing a foundation. We need to
00270    * account for this, as other structures should
00271    * draw the wall of the foundation in this case.
00272    */
00273   if (hid >= NEW_HOUSE_OFFSET) {
00274     const HouseSpec *hs = HouseSpec::Get(hid);
00275     if (hs->grf_prop.spritegroup[0] != NULL && HasBit(hs->callback_mask, CBM_HOUSE_DRAW_FOUNDATIONS)) {
00276       uint32 callback_res = GetHouseCallback(CBID_HOUSE_DRAW_FOUNDATIONS, 0, 0, hid, Town::GetByTile(tile), tile);
00277       if (callback_res != CALLBACK_FAILED && !ConvertBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_DRAW_FOUNDATIONS, callback_res)) return FOUNDATION_NONE;
00278     }
00279   }
00280   return FlatteningFoundation(tileh);
00281 }
00282 
00289 static void AnimateTile_Town(TileIndex tile)
00290 {
00291   if (GetHouseType(tile) >= NEW_HOUSE_OFFSET) {
00292     AnimateNewHouseTile(tile);
00293     return;
00294   }
00295 
00296   if (_tick_counter & 3) return;
00297 
00298   /* If the house is not one with a lift anymore, then stop this animating.
00299    * Not exactly sure when this happens, but probably when a house changes.
00300    * Before this was just a return...so it'd leak animated tiles..
00301    * That bug seems to have been here since day 1?? */
00302   if (!(HouseSpec::Get(GetHouseType(tile))->building_flags & BUILDING_IS_ANIMATED)) {
00303     DeleteAnimatedTile(tile);
00304     return;
00305   }
00306 
00307   if (!LiftHasDestination(tile)) {
00308     uint i;
00309 
00310     /* Building has 6 floors, number 0 .. 6, where 1 is illegal.
00311      * This is due to the fact that the first floor is, in the graphics,
00312      *  the height of 2 'normal' floors.
00313      * Furthermore, there are 6 lift positions from floor N (incl) to floor N + 1 (excl) */
00314     do {
00315       i = RandomRange(7);
00316     } while (i == 1 || i * 6 == GetLiftPosition(tile));
00317 
00318     SetLiftDestination(tile, i);
00319   }
00320 
00321   int pos = GetLiftPosition(tile);
00322   int dest = GetLiftDestination(tile) * 6;
00323   pos += (pos < dest) ? 1 : -1;
00324   SetLiftPosition(tile, pos);
00325 
00326   if (pos == dest) {
00327     HaltLift(tile);
00328     DeleteAnimatedTile(tile);
00329   }
00330 
00331   MarkTileDirtyByTile(tile);
00332 }
00333 
00340 static bool IsCloseToTown(TileIndex tile, uint dist)
00341 {
00342   const Town *t;
00343 
00344   FOR_ALL_TOWNS(t) {
00345     if (DistanceManhattan(tile, t->xy) < dist) return true;
00346   }
00347   return false;
00348 }
00349 
00354 void Town::UpdateVirtCoord()
00355 {
00356   Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
00357   SetDParam(0, this->index);
00358   SetDParam(1, this->cache.population);
00359   this->cache.sign.UpdatePosition(pt.x, pt.y - 24 * ZOOM_LVL_BASE,
00360     _settings_client.gui.population_in_label ? STR_VIEWPORT_TOWN_POP : STR_VIEWPORT_TOWN);
00361 
00362   SetWindowDirty(WC_TOWN_VIEW, this->index);
00363 }
00364 
00366 void UpdateAllTownVirtCoords()
00367 {
00368   Town *t;
00369 
00370   FOR_ALL_TOWNS(t) {
00371     t->UpdateVirtCoord();
00372   }
00373 }
00374 
00380 static void ChangePopulation(Town *t, int mod)
00381 {
00382   t->cache.population += mod;
00383   InvalidateWindowData(WC_TOWN_VIEW, t->index); // Cargo requirements may appear/vanish for small populations
00384   t->UpdateVirtCoord();
00385 
00386   InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
00387 }
00388 
00394 uint32 GetWorldPopulation()
00395 {
00396   uint32 pop = 0;
00397   const Town *t;
00398 
00399   FOR_ALL_TOWNS(t) pop += t->cache.population;
00400   return pop;
00401 }
00402 
00407 static void MakeSingleHouseBigger(TileIndex tile)
00408 {
00409   assert(IsTileType(tile, MP_HOUSE));
00410 
00411   /* progress in construction stages */
00412   IncHouseConstructionTick(tile);
00413   if (GetHouseConstructionTick(tile) != 0) return;
00414 
00415   AnimateNewHouseConstruction(tile);
00416 
00417   if (IsHouseCompleted(tile)) {
00418     /* Now that construction is complete, we can add the population of the
00419      * building to the town. */
00420     ChangePopulation(Town::GetByTile(tile), HouseSpec::Get(GetHouseType(tile))->population);
00421     ResetHouseAge(tile);
00422   }
00423   MarkTileDirtyByTile(tile);
00424 }
00425 
00430 static void MakeTownHouseBigger(TileIndex tile)
00431 {
00432   uint flags = HouseSpec::Get(GetHouseType(tile))->building_flags;
00433   if (flags & BUILDING_HAS_1_TILE)  MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 0));
00434   if (flags & BUILDING_2_TILES_Y)   MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 1));
00435   if (flags & BUILDING_2_TILES_X)   MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 0));
00436   if (flags & BUILDING_HAS_4_TILES) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 1));
00437 }
00438 
00445 static void TileLoop_Town(TileIndex tile)
00446 {
00447   HouseID house_id = GetHouseType(tile);
00448 
00449   /* NewHouseTileLoop returns false if Callback 21 succeeded, i.e. the house
00450    * doesn't exist any more, so don't continue here. */
00451   if (house_id >= NEW_HOUSE_OFFSET && !NewHouseTileLoop(tile)) return;
00452 
00453   if (!IsHouseCompleted(tile)) {
00454     /* Construction is not completed. See if we can go further in construction*/
00455     MakeTownHouseBigger(tile);
00456     return;
00457   }
00458 
00459   const HouseSpec *hs = HouseSpec::Get(house_id);
00460 
00461   /* If the lift has a destination, it is already an animated tile. */
00462   if ((hs->building_flags & BUILDING_IS_ANIMATED) &&
00463       house_id < NEW_HOUSE_OFFSET &&
00464       !LiftHasDestination(tile) &&
00465       Chance16(1, 2)) {
00466     AddAnimatedTile(tile);
00467   }
00468 
00469   Town *t = Town::GetByTile(tile);
00470   uint32 r = Random();
00471 
00472   StationFinder stations(TileArea(tile, 1, 1));
00473 
00474   if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
00475     for (uint i = 0; i < 256; i++) {
00476       uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, r, house_id, t, tile);
00477 
00478       if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
00479 
00480       CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
00481       if (cargo == CT_INVALID) continue;
00482 
00483       uint amt = GB(callback, 0, 8);
00484       if (amt == 0) continue;
00485 
00486       uint moved = MoveGoodsToStation(cargo, amt, ST_TOWN, t->index, stations.GetStations());
00487 
00488       const CargoSpec *cs = CargoSpec::Get(cargo);
00489       t->supplied[cs->Index()].new_max += amt;
00490       t->supplied[cs->Index()].new_act += moved;
00491     }
00492   } else {
00493     if (GB(r, 0, 8) < hs->population) {
00494       uint amt = GB(r, 0, 8) / 8 + 1;
00495 
00496       if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
00497       t->supplied[CT_PASSENGERS].new_max += amt;
00498       t->supplied[CT_PASSENGERS].new_act += MoveGoodsToStation(CT_PASSENGERS, amt, ST_TOWN, t->index, stations.GetStations());
00499     }
00500 
00501     if (GB(r, 8, 8) < hs->mail_generation) {
00502       uint amt = GB(r, 8, 8) / 8 + 1;
00503 
00504       if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
00505       t->supplied[CT_MAIL].new_max += amt;
00506       t->supplied[CT_MAIL].new_act += MoveGoodsToStation(CT_MAIL, amt, ST_TOWN, t->index, stations.GetStations());
00507     }
00508   }
00509 
00510   Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
00511 
00512   if ((hs->building_flags & BUILDING_HAS_1_TILE) &&
00513       HasBit(t->flags, TOWN_IS_FUNDED) &&
00514       CanDeleteHouse(tile) &&
00515       GetHouseAge(tile) >= hs->minimum_life &&
00516       --t->time_until_rebuild == 0) {
00517     t->time_until_rebuild = GB(r, 16, 8) + 192;
00518 
00519     ClearTownHouse(t, tile);
00520 
00521     /* Rebuild with another house? */
00522     if (GB(r, 24, 8) >= 12) BuildTownHouse(t, tile);
00523   }
00524 
00525   cur_company.Restore();
00526 }
00527 
00528 static CommandCost ClearTile_Town(TileIndex tile, DoCommandFlag flags)
00529 {
00530   if (flags & DC_AUTO) return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
00531   if (!CanDeleteHouse(tile)) return CMD_ERROR;
00532 
00533   const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
00534 
00535   CommandCost cost(EXPENSES_CONSTRUCTION);
00536   cost.AddCost(hs->GetRemovalCost());
00537 
00538   int rating = hs->remove_rating_decrease;
00539   Town *t = Town::GetByTile(tile);
00540 
00541   if (Company::IsValidID(_current_company)) {
00542     if (rating > t->ratings[_current_company] && !(flags & DC_NO_TEST_TOWN_RATING) && !_cheats.magic_bulldozer.value) {
00543       SetDParam(0, t->index);
00544       return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
00545     }
00546   }
00547 
00548   ChangeTownRating(t, -rating, RATING_HOUSE_MINIMUM, flags);
00549   if (flags & DC_EXEC) {
00550     ClearTownHouse(t, tile);
00551   }
00552 
00553   return cost;
00554 }
00555 
00556 static void AddProducedCargo_Town(TileIndex tile, CargoArray &produced)
00557 {
00558   HouseID house_id = GetHouseType(tile);
00559   const HouseSpec *hs = HouseSpec::Get(house_id);
00560   Town *t = Town::GetByTile(tile);
00561 
00562   if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
00563     for (uint i = 0; i < 256; i++) {
00564       uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, 0, house_id, t, tile);
00565 
00566       if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
00567 
00568       CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
00569 
00570       if (cargo == CT_INVALID) continue;
00571       produced[cargo]++;
00572     }
00573   } else {
00574     if (hs->population > 0) {
00575       produced[CT_PASSENGERS]++;
00576     }
00577     if (hs->mail_generation > 0) {
00578       produced[CT_MAIL]++;
00579     }
00580   }
00581 }
00582 
00583 static inline void AddAcceptedCargoSetMask(CargoID cargo, uint amount, CargoArray &acceptance, uint32 *always_accepted)
00584 {
00585   if (cargo == CT_INVALID || amount == 0) return;
00586   acceptance[cargo] += amount;
00587   SetBit(*always_accepted, cargo);
00588 }
00589 
00590 static void AddAcceptedCargo_Town(TileIndex tile, CargoArray &acceptance, uint32 *always_accepted)
00591 {
00592   const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
00593   CargoID accepts[3];
00594 
00595   /* Set the initial accepted cargo types */
00596   for (uint8 i = 0; i < lengthof(accepts); i++) {
00597     accepts[i] = hs->accepts_cargo[i];
00598   }
00599 
00600   /* Check for custom accepted cargo types */
00601   if (HasBit(hs->callback_mask, CBM_HOUSE_ACCEPT_CARGO)) {
00602     uint16 callback = GetHouseCallback(CBID_HOUSE_ACCEPT_CARGO, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
00603     if (callback != CALLBACK_FAILED) {
00604       /* Replace accepted cargo types with translated values from callback */
00605       accepts[0] = GetCargoTranslation(GB(callback,  0, 5), hs->grf_prop.grffile);
00606       accepts[1] = GetCargoTranslation(GB(callback,  5, 5), hs->grf_prop.grffile);
00607       accepts[2] = GetCargoTranslation(GB(callback, 10, 5), hs->grf_prop.grffile);
00608     }
00609   }
00610 
00611   /* Check for custom cargo acceptance */
00612   if (HasBit(hs->callback_mask, CBM_HOUSE_CARGO_ACCEPTANCE)) {
00613     uint16 callback = GetHouseCallback(CBID_HOUSE_CARGO_ACCEPTANCE, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
00614     if (callback != CALLBACK_FAILED) {
00615       AddAcceptedCargoSetMask(accepts[0], GB(callback, 0, 4), acceptance, always_accepted);
00616       AddAcceptedCargoSetMask(accepts[1], GB(callback, 4, 4), acceptance, always_accepted);
00617       if (_settings_game.game_creation.landscape != LT_TEMPERATE && HasBit(callback, 12)) {
00618         /* The 'S' bit indicates food instead of goods */
00619         AddAcceptedCargoSetMask(CT_FOOD, GB(callback, 8, 4), acceptance, always_accepted);
00620       } else {
00621         AddAcceptedCargoSetMask(accepts[2], GB(callback, 8, 4), acceptance, always_accepted);
00622       }
00623       return;
00624     }
00625   }
00626 
00627   /* No custom acceptance, so fill in with the default values */
00628   for (uint8 i = 0; i < lengthof(accepts); i++) {
00629     AddAcceptedCargoSetMask(accepts[i], hs->cargo_acceptance[i], acceptance, always_accepted);
00630   }
00631 }
00632 
00633 static void GetTileDesc_Town(TileIndex tile, TileDesc *td)
00634 {
00635   const HouseID house = GetHouseType(tile);
00636   const HouseSpec *hs = HouseSpec::Get(house);
00637   bool house_completed = IsHouseCompleted(tile);
00638 
00639   td->str = hs->building_name;
00640 
00641   uint16 callback_res = GetHouseCallback(CBID_HOUSE_CUSTOM_NAME, house_completed ? 1 : 0, 0, house, Town::GetByTile(tile), tile);
00642   if (callback_res != CALLBACK_FAILED && callback_res != 0x400) {
00643     if (callback_res > 0x400) {
00644       ErrorUnknownCallbackResult(hs->grf_prop.grffile->grfid, CBID_HOUSE_CUSTOM_NAME, callback_res);
00645     } else {
00646       StringID new_name = GetGRFStringID(hs->grf_prop.grffile->grfid, 0xD000 + callback_res);
00647       if (new_name != STR_NULL && new_name != STR_UNDEFINED) {
00648         td->str = new_name;
00649       }
00650     }
00651   }
00652 
00653   if (!house_completed) {
00654     SetDParamX(td->dparam, 0, td->str);
00655     td->str = STR_LAI_TOWN_INDUSTRY_DESCRIPTION_UNDER_CONSTRUCTION;
00656   }
00657 
00658   if (hs->grf_prop.grffile != NULL) {
00659     const GRFConfig *gc = GetGRFConfig(hs->grf_prop.grffile->grfid);
00660     td->grf = gc->GetName();
00661   }
00662 
00663   td->owner[0] = OWNER_TOWN;
00664 }
00665 
00666 static TrackStatus GetTileTrackStatus_Town(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
00667 {
00668   /* not used */
00669   return 0;
00670 }
00671 
00672 static void ChangeTileOwner_Town(TileIndex tile, Owner old_owner, Owner new_owner)
00673 {
00674   /* not used */
00675 }
00676 
00680 void UpdateTownCargoTotal(Town *t)
00681 {
00682   t->cargo_accepted_total = 0;
00683 
00684   const TileArea &area = t->cargo_accepted.GetArea();
00685   TILE_AREA_LOOP(tile, area) {
00686     if (TileX(tile) % AcceptanceMatrix::GRID == 0 && TileY(tile) % AcceptanceMatrix::GRID == 0) {
00687       t->cargo_accepted_total |= t->cargo_accepted[tile];
00688     }
00689   }
00690 }
00691 
00698 static void UpdateTownCargoes(Town *t, TileIndex start, bool update_total = true)
00699 {
00700   CargoArray accepted, produced;
00701   uint32 dummy;
00702 
00703   /* Gather acceptance for all houses in an area around the start tile.
00704    * The area is composed of the square the tile is in, extended one square in all
00705    * directions as the coverage area of a single station is bigger than just one square. */
00706   TileArea area = AcceptanceMatrix::GetAreaForTile(start, 1);
00707   TILE_AREA_LOOP(tile, area) {
00708     if (!IsTileType(tile, MP_HOUSE) || GetTownIndex(tile) != t->index) continue;
00709 
00710     AddAcceptedCargo_Town(tile, accepted, &dummy);
00711     AddProducedCargo_Town(tile, produced);
00712   }
00713 
00714   /* Create bitmap of produced and accepted cargoes. */
00715   uint32 acc = 0;
00716   for (uint cid = 0; cid < NUM_CARGO; cid++) {
00717     if (accepted[cid] >= 8) SetBit(acc, cid);
00718     if (produced[cid] > 0) SetBit(t->cargo_produced, cid);
00719   }
00720   t->cargo_accepted[start] = acc;
00721 
00722   if (update_total) UpdateTownCargoTotal(t);
00723 }
00724 
00728 void UpdateTownCargoes(Town *t)
00729 {
00730   t->cargo_produced = 0;
00731 
00732   const TileArea &area = t->cargo_accepted.GetArea();
00733   if (area.tile == INVALID_TILE) return;
00734 
00735   /* Update acceptance for each grid square. */
00736   TILE_AREA_LOOP(tile, area) {
00737     if (TileX(tile) % AcceptanceMatrix::GRID == 0 && TileY(tile) % AcceptanceMatrix::GRID == 0) {
00738       UpdateTownCargoes(t, tile, false);
00739     }
00740   }
00741 
00742   /* Update the total acceptance. */
00743   UpdateTownCargoTotal(t);
00744 }
00745 
00747 void UpdateTownCargoBitmap()
00748 {
00749   Town *town;
00750   _town_cargoes_accepted = 0;
00751 
00752   FOR_ALL_TOWNS(town) {
00753     _town_cargoes_accepted |= town->cargo_accepted_total;
00754   }
00755 }
00756 
00757 static bool GrowTown(Town *t);
00758 
00759 static void TownTickHandler(Town *t)
00760 {
00761   if (HasBit(t->flags, TOWN_IS_FUNDED)) {
00762     int i = t->grow_counter - 1;
00763     if (i < 0) {
00764       if (GrowTown(t)) {
00765         i = t->growth_rate & (~TOWN_GROW_RATE_CUSTOM);
00766       } else {
00767         i = 0;
00768       }
00769     }
00770     t->grow_counter = i;
00771   }
00772 }
00773 
00774 void OnTick_Town()
00775 {
00776   if (_game_mode == GM_EDITOR) return;
00777 
00778   Town *t;
00779   FOR_ALL_TOWNS(t) {
00780     /* Run town tick at regular intervals, but not all at once. */
00781     if ((_tick_counter + t->index) % TOWN_GROWTH_TICKS == 0) {
00782       TownTickHandler(t);
00783     }
00784   }
00785 }
00786 
00795 static RoadBits GetTownRoadBits(TileIndex tile)
00796 {
00797   if (IsRoadDepotTile(tile) || IsStandardRoadStopTile(tile)) return ROAD_NONE;
00798 
00799   return GetAnyRoadBits(tile, ROADTYPE_ROAD, true);
00800 }
00801 
00812 static bool IsNeighborRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
00813 {
00814   if (!IsValidTile(tile)) return false;
00815 
00816   /* Lookup table for the used diff values */
00817   const TileIndexDiff tid_lt[3] = {
00818     TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90RIGHT)),
00819     TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90LEFT)),
00820     TileOffsByDiagDir(ReverseDiagDir(dir)),
00821   };
00822 
00823   dist_multi = (dist_multi + 1) * 4;
00824   for (uint pos = 4; pos < dist_multi; pos++) {
00825     /* Go (pos / 4) tiles to the left or the right */
00826     TileIndexDiff cur = tid_lt[(pos & 1) ? 0 : 1] * (pos / 4);
00827 
00828     /* Use the current tile as origin, or go one tile backwards */
00829     if (pos & 2) cur += tid_lt[2];
00830 
00831     /* Test for roadbit parallel to dir and facing towards the middle axis */
00832     if (IsValidTile(tile + cur) &&
00833         GetTownRoadBits(TILE_ADD(tile, cur)) & DiagDirToRoadBits((pos & 2) ? dir : ReverseDiagDir(dir))) return true;
00834   }
00835   return false;
00836 }
00837 
00846 static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
00847 {
00848   if (DistanceFromEdge(tile) == 0) return false;
00849 
00850   /* Check if there already is a road at this point? */
00851   if (GetTownRoadBits(tile) == ROAD_NONE) {
00852     /* No, try if we are able to build a road piece there.
00853      * If that fails clear the land, and if that fails exit.
00854      * This is to make sure that we can build a road here later. */
00855     if (DoCommand(tile, ((dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? ROAD_Y : ROAD_X), 0, DC_AUTO, CMD_BUILD_ROAD).Failed() &&
00856         DoCommand(tile, 0, 0, DC_AUTO, CMD_LANDSCAPE_CLEAR).Failed()) {
00857       return false;
00858     }
00859   }
00860 
00861   Slope cur_slope = _settings_game.construction.build_on_slopes ? GetFoundationSlope(tile) : GetTileSlope(tile);
00862   bool ret = !IsNeighborRoadTile(tile, dir, t->layout == TL_ORIGINAL ? 1 : 2);
00863   if (cur_slope == SLOPE_FLAT) return ret;
00864 
00865   /* If the tile is not a slope in the right direction, then
00866    * maybe terraform some. */
00867   Slope desired_slope = (dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? SLOPE_NW : SLOPE_NE;
00868   if (desired_slope != cur_slope && ComplementSlope(desired_slope) != cur_slope) {
00869     if (Chance16(1, 8)) {
00870       CommandCost res = CMD_ERROR;
00871       if (!_generating_world && Chance16(1, 10)) {
00872         /* Note: Do not replace "^ SLOPE_ELEVATED" with ComplementSlope(). The slope might be steep. */
00873         res = DoCommand(tile, Chance16(1, 16) ? cur_slope : cur_slope ^ SLOPE_ELEVATED, 0,
00874             DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
00875       }
00876       if (res.Failed() && Chance16(1, 3)) {
00877         /* We can consider building on the slope, though. */
00878         return ret;
00879       }
00880     }
00881     return false;
00882   }
00883   return ret;
00884 }
00885 
00886 static bool TerraformTownTile(TileIndex tile, int edges, int dir)
00887 {
00888   assert(tile < MapSize());
00889 
00890   CommandCost r = DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
00891   if (r.Failed() || r.GetCost() >= (_price[PR_TERRAFORM] + 2) * 8) return false;
00892   DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER | DC_EXEC, CMD_TERRAFORM_LAND);
00893   return true;
00894 }
00895 
00896 static void LevelTownLand(TileIndex tile)
00897 {
00898   assert(tile < MapSize());
00899 
00900   /* Don't terraform if land is plain or if there's a house there. */
00901   if (IsTileType(tile, MP_HOUSE)) return;
00902   Slope tileh = GetTileSlope(tile);
00903   if (tileh == SLOPE_FLAT) return;
00904 
00905   /* First try up, then down */
00906   if (!TerraformTownTile(tile, ~tileh & SLOPE_ELEVATED, 1)) {
00907     TerraformTownTile(tile, tileh & SLOPE_ELEVATED, 0);
00908   }
00909 }
00910 
00920 static RoadBits GetTownRoadGridElement(Town *t, TileIndex tile, DiagDirection dir)
00921 {
00922   /* align the grid to the downtown */
00923   TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile); // Vector from downtown to the tile
00924   RoadBits rcmd = ROAD_NONE;
00925 
00926   switch (t->layout) {
00927     default: NOT_REACHED();
00928 
00929     case TL_2X2_GRID:
00930       if ((grid_pos.x % 3) == 0) rcmd |= ROAD_Y;
00931       if ((grid_pos.y % 3) == 0) rcmd |= ROAD_X;
00932       break;
00933 
00934     case TL_3X3_GRID:
00935       if ((grid_pos.x % 4) == 0) rcmd |= ROAD_Y;
00936       if ((grid_pos.y % 4) == 0) rcmd |= ROAD_X;
00937       break;
00938   }
00939 
00940   /* Optimise only X-junctions */
00941   if (rcmd != ROAD_ALL) return rcmd;
00942 
00943   RoadBits rb_template;
00944 
00945   switch (GetTileSlope(tile)) {
00946     default:       rb_template = ROAD_ALL; break;
00947     case SLOPE_W:  rb_template = ROAD_NW | ROAD_SW; break;
00948     case SLOPE_SW: rb_template = ROAD_Y  | ROAD_SW; break;
00949     case SLOPE_S:  rb_template = ROAD_SW | ROAD_SE; break;
00950     case SLOPE_SE: rb_template = ROAD_X  | ROAD_SE; break;
00951     case SLOPE_E:  rb_template = ROAD_SE | ROAD_NE; break;
00952     case SLOPE_NE: rb_template = ROAD_Y  | ROAD_NE; break;
00953     case SLOPE_N:  rb_template = ROAD_NE | ROAD_NW; break;
00954     case SLOPE_NW: rb_template = ROAD_X  | ROAD_NW; break;
00955     case SLOPE_STEEP_W:
00956     case SLOPE_STEEP_S:
00957     case SLOPE_STEEP_E:
00958     case SLOPE_STEEP_N:
00959       rb_template = ROAD_NONE;
00960       break;
00961   }
00962 
00963   /* Stop if the template is compatible to the growth dir */
00964   if (DiagDirToRoadBits(ReverseDiagDir(dir)) & rb_template) return rb_template;
00965   /* If not generate a straight road in the direction of the growth */
00966   return DiagDirToRoadBits(dir) | DiagDirToRoadBits(ReverseDiagDir(dir));
00967 }
00968 
00979 static bool GrowTownWithExtraHouse(Town *t, TileIndex tile)
00980 {
00981   /* We can't look further than that. */
00982   if (DistanceFromEdge(tile) == 0) return false;
00983 
00984   uint counter = 0; // counts the house neighbor tiles
00985 
00986   /* Check the tiles E,N,W and S of the current tile for houses */
00987   for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
00988     /* Count both void and house tiles for checking whether there
00989      * are enough houses in the area. This to make it likely that
00990      * houses get build up to the edge of the map. */
00991     switch (GetTileType(TileAddByDiagDir(tile, dir))) {
00992       case MP_HOUSE:
00993       case MP_VOID:
00994         counter++;
00995         break;
00996 
00997       default:
00998         break;
00999     }
01000 
01001     /* If there are enough neighbors stop here */
01002     if (counter >= 3) {
01003       if (BuildTownHouse(t, tile)) {
01004         _grow_town_result = GROWTH_SUCCEED;
01005         return true;
01006       }
01007       return false;
01008     }
01009   }
01010   return false;
01011 }
01012 
01021 static bool GrowTownWithRoad(const Town *t, TileIndex tile, RoadBits rcmd)
01022 {
01023   if (DoCommand(tile, rcmd, t->index, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD).Succeeded()) {
01024     _grow_town_result = GROWTH_SUCCEED;
01025     return true;
01026   }
01027   return false;
01028 }
01029 
01040 static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
01041 {
01042   assert(bridge_dir < DIAGDIR_END);
01043 
01044   const Slope slope = GetTileSlope(tile);
01045 
01046   /* Make sure the direction is compatible with the slope.
01047    * Well we check if the slope has an up bit set in the
01048    * reverse direction. */
01049   if (slope != SLOPE_FLAT && slope & InclinedSlope(bridge_dir)) return false;
01050 
01051   /* Assure that the bridge is connectable to the start side */
01052   if (!(GetTownRoadBits(TileAddByDiagDir(tile, ReverseDiagDir(bridge_dir))) & DiagDirToRoadBits(bridge_dir))) return false;
01053 
01054   /* We are in the right direction */
01055   uint8 bridge_length = 0;      // This value stores the length of the possible bridge
01056   TileIndex bridge_tile = tile; // Used to store the other waterside
01057 
01058   const int delta = TileOffsByDiagDir(bridge_dir);
01059 
01060   if (slope == SLOPE_FLAT) {
01061     /* Bridges starting on flat tiles are only allowed when crossing rivers. */
01062     do {
01063       if (bridge_length++ >= 4) {
01064         /* Allow to cross rivers, not big lakes. */
01065         return false;
01066       }
01067       bridge_tile += delta;
01068     } while (IsValidTile(bridge_tile) && IsWaterTile(bridge_tile) && !IsSea(bridge_tile));
01069   } else {
01070     do {
01071       if (bridge_length++ >= 11) {
01072         /* Max 11 tile long bridges */
01073         return false;
01074       }
01075       bridge_tile += delta;
01076     } while (IsValidTile(bridge_tile) && IsWaterTile(bridge_tile));
01077   }
01078 
01079   /* no water tiles in between? */
01080   if (bridge_length == 1) return false;
01081 
01082   for (uint8 times = 0; times <= 22; times++) {
01083     byte bridge_type = RandomRange(MAX_BRIDGES - 1);
01084 
01085     /* Can we actually build the bridge? */
01086     if (DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)), CMD_BUILD_BRIDGE).Succeeded()) {
01087       DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, DC_EXEC | CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)), CMD_BUILD_BRIDGE);
01088       _grow_town_result = GROWTH_SUCCEED;
01089       return true;
01090     }
01091   }
01092   /* Quit if it selecting an appropiate bridge type fails a large number of times. */
01093   return false;
01094 }
01095 
01113 static void GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1)
01114 {
01115   RoadBits rcmd = ROAD_NONE;  // RoadBits for the road construction command
01116   TileIndex tile = *tile_ptr; // The main tile on which we base our growth
01117 
01118   assert(tile < MapSize());
01119 
01120   if (cur_rb == ROAD_NONE) {
01121     /* Tile has no road. First reset the status counter
01122      * to say that this is the last iteration. */
01123     _grow_town_result = GROWTH_SEARCH_STOPPED;
01124 
01125     if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
01126     if (!_settings_game.economy.allow_town_level_crossings && IsTileType(tile, MP_RAILWAY)) return;
01127 
01128     /* Remove hills etc */
01129     if (!_settings_game.construction.build_on_slopes || Chance16(1, 6)) LevelTownLand(tile);
01130 
01131     /* Is a road allowed here? */
01132     switch (t1->layout) {
01133       default: NOT_REACHED();
01134 
01135       case TL_3X3_GRID:
01136       case TL_2X2_GRID:
01137         rcmd = GetTownRoadGridElement(t1, tile, target_dir);
01138         if (rcmd == ROAD_NONE) return;
01139         break;
01140 
01141       case TL_BETTER_ROADS:
01142       case TL_ORIGINAL:
01143         if (!IsRoadAllowedHere(t1, tile, target_dir)) return;
01144 
01145         DiagDirection source_dir = ReverseDiagDir(target_dir);
01146 
01147         if (Chance16(1, 4)) {
01148           /* Randomize a new target dir */
01149           do target_dir = RandomDiagDir(); while (target_dir == source_dir);
01150         }
01151 
01152         if (!IsRoadAllowedHere(t1, TileAddByDiagDir(tile, target_dir), target_dir)) {
01153           /* A road is not allowed to continue the randomized road,
01154            *  return if the road we're trying to build is curved. */
01155           if (target_dir != ReverseDiagDir(source_dir)) return;
01156 
01157           /* Return if neither side of the new road is a house */
01158           if (!IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90RIGHT)), MP_HOUSE) &&
01159               !IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90LEFT)), MP_HOUSE)) {
01160             return;
01161           }
01162 
01163           /* That means that the road is only allowed if there is a house
01164            *  at any side of the new road. */
01165         }
01166 
01167         rcmd = DiagDirToRoadBits(target_dir) | DiagDirToRoadBits(source_dir);
01168         break;
01169     }
01170 
01171   } else if (target_dir < DIAGDIR_END && !(cur_rb & DiagDirToRoadBits(ReverseDiagDir(target_dir)))) {
01172     /* Continue building on a partial road.
01173      * Should be allways OK, so we only generate
01174      * the fitting RoadBits */
01175     _grow_town_result = GROWTH_SEARCH_STOPPED;
01176 
01177     if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
01178 
01179     switch (t1->layout) {
01180       default: NOT_REACHED();
01181 
01182       case TL_3X3_GRID:
01183       case TL_2X2_GRID:
01184         rcmd = GetTownRoadGridElement(t1, tile, target_dir);
01185         break;
01186 
01187       case TL_BETTER_ROADS:
01188       case TL_ORIGINAL:
01189         rcmd = DiagDirToRoadBits(ReverseDiagDir(target_dir));
01190         break;
01191     }
01192   } else {
01193     bool allow_house = true; // Value which decides if we want to construct a house
01194 
01195     /* Reached a tunnel/bridge? Then continue at the other side of it, unless
01196      * it is the starting tile. Half the time, we stay on this side then.*/
01197     if (IsTileType(tile, MP_TUNNELBRIDGE)) {
01198       if (GetTunnelBridgeTransportType(tile) == TRANSPORT_ROAD && (target_dir != DIAGDIR_END || Chance16(1, 2))) {
01199         *tile_ptr = GetOtherTunnelBridgeEnd(tile);
01200       }
01201       return;
01202     }
01203 
01204     /* Possibly extend the road in a direction.
01205      * Randomize a direction and if it has a road, bail out. */
01206     target_dir = RandomDiagDir();
01207     if (cur_rb & DiagDirToRoadBits(target_dir)) return;
01208 
01209     /* This is the tile we will reach if we extend to this direction. */
01210     TileIndex house_tile = TileAddByDiagDir(tile, target_dir); // position of a possible house
01211 
01212     /* Don't walk into water. */
01213     if (HasTileWaterGround(house_tile)) return;
01214 
01215     if (!IsValidTile(house_tile)) return;
01216 
01217     if (_settings_game.economy.allow_town_roads || _generating_world) {
01218       switch (t1->layout) {
01219         default: NOT_REACHED();
01220 
01221         case TL_3X3_GRID: // Use 2x2 grid afterwards!
01222           GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
01223           /* FALL THROUGH */
01224 
01225         case TL_2X2_GRID:
01226           rcmd = GetTownRoadGridElement(t1, house_tile, target_dir);
01227           allow_house = (rcmd == ROAD_NONE);
01228           break;
01229 
01230         case TL_BETTER_ROADS: // Use original afterwards!
01231           GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
01232           /* FALL THROUGH */
01233 
01234         case TL_ORIGINAL:
01235           /* Allow a house at the edge. 60% chance or
01236            * always ok if no road allowed. */
01237           rcmd = DiagDirToRoadBits(target_dir);
01238           allow_house = (!IsRoadAllowedHere(t1, house_tile, target_dir) || Chance16(6, 10));
01239           break;
01240       }
01241     }
01242 
01243     if (allow_house) {
01244       /* Build a house, but not if there already is a house there. */
01245       if (!IsTileType(house_tile, MP_HOUSE)) {
01246         /* Level the land if possible */
01247         if (Chance16(1, 6)) LevelTownLand(house_tile);
01248 
01249         /* And build a house.
01250          * Set result to -1 if we managed to build it. */
01251         if (BuildTownHouse(t1, house_tile)) {
01252           _grow_town_result = GROWTH_SUCCEED;
01253         }
01254       }
01255       return;
01256     }
01257 
01258     _grow_town_result = GROWTH_SEARCH_STOPPED;
01259   }
01260 
01261   /* Return if a water tile */
01262   if (HasTileWaterGround(tile)) return;
01263 
01264   /* Make the roads look nicer */
01265   rcmd = CleanUpRoadBits(tile, rcmd);
01266   if (rcmd == ROAD_NONE) return;
01267 
01268   /* Only use the target direction for bridges to ensure they're connected.
01269    * The target_dir is as computed previously according to town layout, so
01270    * it will match it perfectly. */
01271   if (GrowTownWithBridge(t1, tile, target_dir)) return;
01272 
01273   GrowTownWithRoad(t1, tile, rcmd);
01274 }
01275 
01282 static int GrowTownAtRoad(Town *t, TileIndex tile)
01283 {
01284   /* Special case.
01285    * @see GrowTownInTile Check the else if
01286    */
01287   DiagDirection target_dir = DIAGDIR_END; // The direction in which we want to extend the town
01288 
01289   assert(tile < MapSize());
01290 
01291   /* Number of times to search.
01292    * Better roads, 2X2 and 3X3 grid grow quite fast so we give
01293    * them a little handicap. */
01294   switch (t->layout) {
01295     case TL_BETTER_ROADS:
01296       _grow_town_result = 10 + t->cache.num_houses * 2 / 9;
01297       break;
01298 
01299     case TL_3X3_GRID:
01300     case TL_2X2_GRID:
01301       _grow_town_result = 10 + t->cache.num_houses * 1 / 9;
01302       break;
01303 
01304     default:
01305       _grow_town_result = 10 + t->cache.num_houses * 4 / 9;
01306       break;
01307   }
01308 
01309   do {
01310     RoadBits cur_rb = GetTownRoadBits(tile); // The RoadBits of the current tile
01311 
01312     /* Try to grow the town from this point */
01313     GrowTownInTile(&tile, cur_rb, target_dir, t);
01314 
01315     /* Exclude the source position from the bitmask
01316      * and return if no more road blocks available */
01317     cur_rb &= ~DiagDirToRoadBits(ReverseDiagDir(target_dir));
01318     if (cur_rb == ROAD_NONE) {
01319       return _grow_town_result;
01320     }
01321 
01322     if (IsTileType(tile, MP_TUNNELBRIDGE)) {
01323       /* Only build in the direction away from the tunnel or bridge. */
01324       target_dir = ReverseDiagDir(GetTunnelBridgeDirection(tile));
01325     } else {
01326       /* Select a random bit from the blockmask, walk a step
01327        * and continue the search from there. */
01328       do target_dir = RandomDiagDir(); while (!(cur_rb & DiagDirToRoadBits(target_dir)));
01329     }
01330     tile = TileAddByDiagDir(tile, target_dir);
01331 
01332     if (IsTileType(tile, MP_ROAD) && !IsRoadDepot(tile) && HasTileRoadType(tile, ROADTYPE_ROAD)) {
01333       /* Don't allow building over roads of other cities */
01334       if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN) && Town::GetByTile(tile) != t) {
01335         _grow_town_result = GROWTH_SUCCEED;
01336       } else if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_NONE) && _game_mode == GM_EDITOR) {
01337         /* If we are in the SE, and this road-piece has no town owner yet, it just found an
01338          * owner :) (happy happy happy road now) */
01339         SetRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN);
01340         SetTownIndex(tile, t->index);
01341       }
01342     }
01343 
01344     /* Max number of times is checked. */
01345   } while (--_grow_town_result >= 0);
01346 
01347   return (_grow_town_result == -2);
01348 }
01349 
01357 static RoadBits GenRandomRoadBits()
01358 {
01359   uint32 r = Random();
01360   uint a = GB(r, 0, 2);
01361   uint b = GB(r, 8, 2);
01362   if (a == b) b ^= 2;
01363   return (RoadBits)((ROAD_NW << a) + (ROAD_NW << b));
01364 }
01365 
01371 static bool GrowTown(Town *t)
01372 {
01373   static const TileIndexDiffC _town_coord_mod[] = {
01374     {-1,  0},
01375     { 1,  1},
01376     { 1, -1},
01377     {-1, -1},
01378     {-1,  0},
01379     { 0,  2},
01380     { 2,  0},
01381     { 0, -2},
01382     {-1, -1},
01383     {-2,  2},
01384     { 2,  2},
01385     { 2, -2},
01386     { 0,  0}
01387   };
01388 
01389   /* Current "company" is a town */
01390   Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
01391 
01392   TileIndex tile = t->xy; // The tile we are working with ATM
01393 
01394   /* Find a road that we can base the construction on. */
01395   const TileIndexDiffC *ptr;
01396   for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
01397     if (GetTownRoadBits(tile) != ROAD_NONE) {
01398       int r = GrowTownAtRoad(t, tile);
01399       cur_company.Restore();
01400       return r != 0;
01401     }
01402     tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
01403   }
01404 
01405   /* No road available, try to build a random road block by
01406    * clearing some land and then building a road there. */
01407   if (_settings_game.economy.allow_town_roads || _generating_world) {
01408     tile = t->xy;
01409     for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
01410       /* Only work with plain land that not already has a house */
01411       if (!IsTileType(tile, MP_HOUSE) && GetTileSlope(tile) == SLOPE_FLAT) {
01412         if (DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded()) {
01413           DoCommand(tile, GenRandomRoadBits(), t->index, DC_EXEC | DC_AUTO, CMD_BUILD_ROAD);
01414           cur_company.Restore();
01415           return true;
01416         }
01417       }
01418       tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
01419     }
01420   }
01421 
01422   cur_company.Restore();
01423   return false;
01424 }
01425 
01426 void UpdateTownRadius(Town *t)
01427 {
01428   static const uint32 _town_squared_town_zone_radius_data[23][5] = {
01429     {  4,  0,  0,  0,  0}, // 0
01430     { 16,  0,  0,  0,  0},
01431     { 25,  0,  0,  0,  0},
01432     { 36,  0,  0,  0,  0},
01433     { 49,  0,  4,  0,  0},
01434     { 64,  0,  4,  0,  0}, // 20
01435     { 64,  0,  9,  0,  1},
01436     { 64,  0,  9,  0,  4},
01437     { 64,  0, 16,  0,  4},
01438     { 81,  0, 16,  0,  4},
01439     { 81,  0, 16,  0,  4}, // 40
01440     { 81,  0, 25,  0,  9},
01441     { 81, 36, 25,  0,  9},
01442     { 81, 36, 25, 16,  9},
01443     { 81, 49,  0, 25,  9},
01444     { 81, 64,  0, 25,  9}, // 60
01445     { 81, 64,  0, 36,  9},
01446     { 81, 64,  0, 36, 16},
01447     {100, 81,  0, 49, 16},
01448     {100, 81,  0, 49, 25},
01449     {121, 81,  0, 49, 25}, // 80
01450     {121, 81,  0, 49, 25},
01451     {121, 81,  0, 49, 36}, // 88
01452   };
01453 
01454   if (t->cache.num_houses < 92) {
01455     memcpy(t->cache.squared_town_zone_radius, _town_squared_town_zone_radius_data[t->cache.num_houses / 4], sizeof(t->cache.squared_town_zone_radius));
01456   } else {
01457     int mass = t->cache.num_houses / 8;
01458     /* Actually we are proportional to sqrt() but that's right because we are covering an area.
01459      * The offsets are to make sure the radii do not decrease in size when going from the table
01460      * to the calculated value.*/
01461     t->cache.squared_town_zone_radius[0] = mass * 15 - 40;
01462     t->cache.squared_town_zone_radius[1] = mass * 9 - 15;
01463     t->cache.squared_town_zone_radius[2] = 0;
01464     t->cache.squared_town_zone_radius[3] = mass * 5 - 5;
01465     t->cache.squared_town_zone_radius[4] = mass * 3 + 5;
01466   }
01467 }
01468 
01469 void UpdateTownMaxPass(Town *t)
01470 {
01471   t->supplied[CT_PASSENGERS].old_max = t->cache.population >> 3;
01472   t->supplied[CT_MAIL].old_max = t->cache.population >> 4;
01473 }
01474 
01486 static void DoCreateTown(Town *t, TileIndex tile, uint32 townnameparts, TownSize size, bool city, TownLayout layout, bool manual)
01487 {
01488   t->xy = tile;
01489   t->cache.num_houses = 0;
01490   t->time_until_rebuild = 10;
01491   UpdateTownRadius(t);
01492   t->flags = 0;
01493   t->cache.population = 0;
01494   t->grow_counter = 0;
01495   t->growth_rate = 250;
01496 
01497   /* Set the default cargo requirement for town growth */
01498   switch (_settings_game.game_creation.landscape) {
01499     case LT_ARCTIC:
01500       if (FindFirstCargoWithTownEffect(TE_FOOD) != NULL) t->goal[TE_FOOD] = TOWN_GROWTH_WINTER;
01501       break;
01502 
01503     case LT_TROPIC:
01504       if (FindFirstCargoWithTownEffect(TE_FOOD) != NULL) t->goal[TE_FOOD] = TOWN_GROWTH_DESERT;
01505       if (FindFirstCargoWithTownEffect(TE_WATER) != NULL) t->goal[TE_WATER] = TOWN_GROWTH_DESERT;
01506       break;
01507   }
01508 
01509   t->fund_buildings_months = 0;
01510 
01511   for (uint i = 0; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
01512 
01513   t->have_ratings = 0;
01514   t->exclusivity = INVALID_COMPANY;
01515   t->exclusive_counter = 0;
01516   t->statues = 0;
01517 
01518   extern int _nb_orig_names;
01519   if (_settings_game.game_creation.town_name < _nb_orig_names) {
01520     /* Original town name */
01521     t->townnamegrfid = 0;
01522     t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
01523   } else {
01524     /* Newgrf town name */
01525     t->townnamegrfid = GetGRFTownNameId(_settings_game.game_creation.town_name  - _nb_orig_names);
01526     t->townnametype  = GetGRFTownNameType(_settings_game.game_creation.town_name - _nb_orig_names);
01527   }
01528   t->townnameparts = townnameparts;
01529 
01530   t->UpdateVirtCoord();
01531   InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
01532 
01533   t->InitializeLayout(layout);
01534 
01535   t->larger_town = city;
01536 
01537   int x = (int)size * 16 + 3;
01538   if (size == TSZ_RANDOM) x = (Random() & 0xF) + 8;
01539   /* Don't create huge cities when founding town in-game */
01540   if (city && (!manual || _game_mode == GM_EDITOR)) x *= _settings_game.economy.initial_city_size;
01541 
01542   t->cache.num_houses += x;
01543   UpdateTownRadius(t);
01544 
01545   int i = x * 4;
01546   do {
01547     GrowTown(t);
01548   } while (--i);
01549 
01550   t->cache.num_houses -= x;
01551   UpdateTownRadius(t);
01552   UpdateTownMaxPass(t);
01553   UpdateAirportsNoise();
01554 }
01555 
01561 static CommandCost TownCanBePlacedHere(TileIndex tile)
01562 {
01563   /* Check if too close to the edge of map */
01564   if (DistanceFromEdge(tile) < 12) {
01565     return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP_SUB);
01566   }
01567 
01568   /* Check distance to all other towns. */
01569   if (IsCloseToTown(tile, 20)) {
01570     return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_TOWN);
01571   }
01572 
01573   /* Can only build on clear flat areas, possibly with trees. */
01574   if ((!IsTileType(tile, MP_CLEAR) && !IsTileType(tile, MP_TREES)) || GetTileSlope(tile) != SLOPE_FLAT) {
01575     return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
01576   }
01577 
01578   return CommandCost(EXPENSES_OTHER);
01579 }
01580 
01586 static bool IsUniqueTownName(const char *name)
01587 {
01588   const Town *t;
01589 
01590   FOR_ALL_TOWNS(t) {
01591     if (t->name != NULL && strcmp(t->name, name) == 0) return false;
01592   }
01593 
01594   return true;
01595 }
01596 
01609 CommandCost CmdFoundTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01610 {
01611   TownSize size = Extract<TownSize, 0, 2>(p1);
01612   bool city = HasBit(p1, 2);
01613   TownLayout layout = Extract<TownLayout, 3, 3>(p1);
01614   TownNameParams par(_settings_game.game_creation.town_name);
01615   bool random = HasBit(p1, 6);
01616   uint32 townnameparts = p2;
01617 
01618   if (size >= TSZ_END) return CMD_ERROR;
01619   if (layout >= NUM_TLS) return CMD_ERROR;
01620 
01621   /* Some things are allowed only in the scenario editor */
01622   if (_game_mode != GM_EDITOR) {
01623     if (_settings_game.economy.found_town == TF_FORBIDDEN) return CMD_ERROR;
01624     if (size == TSZ_LARGE) return CMD_ERROR;
01625     if (random) return CMD_ERROR;
01626     if (_settings_game.economy.found_town != TF_CUSTOM_LAYOUT && layout != _settings_game.economy.town_layout) {
01627       return CMD_ERROR;
01628     }
01629   }
01630 
01631   if (StrEmpty(text)) {
01632     /* If supplied name is empty, townnameparts has to generate unique automatic name */
01633     if (!VerifyTownName(townnameparts, &par)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
01634   } else {
01635     /* If name is not empty, it has to be unique custom name */
01636     if (Utf8StringLength(text) >= MAX_LENGTH_TOWN_NAME_CHARS) return CMD_ERROR;
01637     if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
01638   }
01639 
01640   /* Allocate town struct */
01641   if (!Town::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_TOWNS);
01642 
01643   if (!random) {
01644     CommandCost ret = TownCanBePlacedHere(tile);
01645     if (ret.Failed()) return ret;
01646   }
01647 
01648   static const byte price_mult[][TSZ_RANDOM + 1] = {{ 15, 25, 40, 25 }, { 20, 35, 55, 35 }};
01649   /* multidimensional arrays have to have defined length of non-first dimension */
01650   assert_compile(lengthof(price_mult[0]) == 4);
01651 
01652   CommandCost cost(EXPENSES_OTHER, _price[PR_BUILD_TOWN]);
01653   byte mult = price_mult[city][size];
01654 
01655   cost.MultiplyCost(mult);
01656 
01657   /* Create the town */
01658   if (flags & DC_EXEC) {
01659     if (cost.GetCost() > GetAvailableMoneyForCommand()) {
01660       _additional_cash_required = cost.GetCost();
01661       return CommandCost(EXPENSES_OTHER);
01662     }
01663 
01664     _generating_world = true;
01665     UpdateNearestTownForRoadTiles(true);
01666     Town *t;
01667     if (random) {
01668       t = CreateRandomTown(20, townnameparts, size, city, layout);
01669       if (t == NULL) {
01670         cost = CommandCost(STR_ERROR_NO_SPACE_FOR_TOWN);
01671       } else {
01672         _new_town_id = t->index;
01673       }
01674     } else {
01675       t = new Town(tile);
01676       DoCreateTown(t, tile, townnameparts, size, city, layout, true);
01677     }
01678     UpdateNearestTownForRoadTiles(false);
01679     _generating_world = false;
01680 
01681     if (t != NULL && !StrEmpty(text)) {
01682       t->name = strdup(text);
01683       t->UpdateVirtCoord();
01684     }
01685 
01686     if (_game_mode != GM_EDITOR) {
01687       /* 't' can't be NULL since 'random' is false outside scenedit */
01688       assert(!random);
01689       char company_name[MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH];
01690       SetDParam(0, _current_company);
01691       GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
01692 
01693       char *cn = strdup(company_name);
01694       SetDParamStr(0, cn);
01695       SetDParam(1, t->index);
01696 
01697       AddNewsItem(STR_NEWS_NEW_TOWN, NS_INDUSTRY_OPEN, NR_TILE, tile, NR_NONE, UINT32_MAX, cn);
01698       AI::BroadcastNewEvent(new ScriptEventTownFounded(t->index));
01699       Game::NewEvent(new ScriptEventTownFounded(t->index));
01700     }
01701   }
01702   return cost;
01703 }
01704 
01714 static TileIndex AlignTileToGrid(TileIndex tile, TownLayout layout)
01715 {
01716   switch (layout) {
01717     case TL_2X2_GRID: return TileXY(TileX(tile) - TileX(tile) % 3, TileY(tile) - TileY(tile) % 3);
01718     case TL_3X3_GRID: return TileXY(TileX(tile) & ~3, TileY(tile) & ~3);
01719     default:          return tile;
01720   }
01721 }
01722 
01732 static bool IsTileAlignedToGrid(TileIndex tile, TownLayout layout)
01733 {
01734   switch (layout) {
01735     case TL_2X2_GRID: return TileX(tile) % 3 == 0 && TileY(tile) % 3 == 0;
01736     case TL_3X3_GRID: return TileX(tile) % 4 == 0 && TileY(tile) % 4 == 0;
01737     default:          return true;
01738   }
01739 }
01740 
01744 struct SpotData {
01745   TileIndex tile; 
01746   uint max_dist;  
01747   TownLayout layout; 
01748 };
01749 
01766 static bool FindFurthestFromWater(TileIndex tile, void *user_data)
01767 {
01768   SpotData *sp = (SpotData*)user_data;
01769   uint dist = GetClosestWaterDistance(tile, true);
01770 
01771   if (IsTileType(tile, MP_CLEAR) &&
01772       GetTileSlope(tile) == SLOPE_FLAT &&
01773       IsTileAlignedToGrid(tile, sp->layout) &&
01774       dist > sp->max_dist) {
01775     sp->tile = tile;
01776     sp->max_dist = dist;
01777   }
01778 
01779   return false;
01780 }
01781 
01788 static bool FindNearestEmptyLand(TileIndex tile, void *user_data)
01789 {
01790   return IsTileType(tile, MP_CLEAR);
01791 }
01792 
01805 static TileIndex FindNearestGoodCoastalTownSpot(TileIndex tile, TownLayout layout)
01806 {
01807   SpotData sp = { INVALID_TILE, 0, layout };
01808 
01809   TileIndex coast = tile;
01810   if (CircularTileSearch(&coast, 40, FindNearestEmptyLand, NULL)) {
01811     CircularTileSearch(&coast, 10, FindFurthestFromWater, &sp);
01812     return sp.tile;
01813   }
01814 
01815   /* if we get here just give up */
01816   return INVALID_TILE;
01817 }
01818 
01819 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout)
01820 {
01821   assert(_game_mode == GM_EDITOR || _generating_world); // These are the preconditions for CMD_DELETE_TOWN
01822 
01823   if (!Town::CanAllocateItem()) return NULL;
01824 
01825   do {
01826     /* Generate a tile index not too close from the edge */
01827     TileIndex tile = AlignTileToGrid(RandomTile(), layout);
01828 
01829     /* if we tried to place the town on water, slide it over onto
01830      * the nearest likely-looking spot */
01831     if (IsTileType(tile, MP_WATER)) {
01832       tile = FindNearestGoodCoastalTownSpot(tile, layout);
01833       if (tile == INVALID_TILE) continue;
01834     }
01835 
01836     /* Make sure town can be placed here */
01837     if (TownCanBePlacedHere(tile).Failed()) continue;
01838 
01839     /* Allocate a town struct */
01840     Town *t = new Town(tile);
01841 
01842     DoCreateTown(t, tile, townnameparts, size, city, layout, false);
01843 
01844     /* if the population is still 0 at the point, then the
01845      * placement is so bad it couldn't grow at all */
01846     if (t->cache.population > 0) return t;
01847     CommandCost rc = DoCommand(t->xy, t->index, 0, DC_EXEC, CMD_DELETE_TOWN);
01848     assert(rc.Succeeded());
01849 
01850     /* We already know that we can allocate a single town when
01851      * entering this function. However, we create and delete
01852      * a town which "resets" the allocation checks. As such we
01853      * need to check again when assertions are enabled. */
01854     assert(Town::CanAllocateItem());
01855   } while (--attempts != 0);
01856 
01857   return NULL;
01858 }
01859 
01860 static const byte _num_initial_towns[4] = {5, 11, 23, 46};  // very low, low, normal, high
01861 
01869 bool GenerateTowns(TownLayout layout)
01870 {
01871   uint current_number = 0;
01872   uint difficulty = (_game_mode != GM_EDITOR) ? _settings_game.difficulty.number_towns : 0;
01873   uint total = (difficulty == (uint)CUSTOM_TOWN_NUMBER_DIFFICULTY) ? _settings_game.game_creation.custom_town_number : ScaleByMapSize(_num_initial_towns[difficulty] + (Random() & 7));
01874   uint32 townnameparts;
01875 
01876   SetGeneratingWorldProgress(GWP_TOWN, total);
01877 
01878   /* First attempt will be made at creating the suggested number of towns.
01879    * Note that this is really a suggested value, not a required one.
01880    * We would not like the system to lock up just because the user wanted 100 cities on a 64*64 map, would we? */
01881   do {
01882     bool city = (_settings_game.economy.larger_towns != 0 && Chance16(1, _settings_game.economy.larger_towns));
01883     IncreaseGeneratingWorldProgress(GWP_TOWN);
01884     /* Get a unique name for the town. */
01885     if (!GenerateTownName(&townnameparts)) continue;
01886     /* try 20 times to create a random-sized town for the first loop. */
01887     if (CreateRandomTown(20, townnameparts, TSZ_RANDOM, city, layout) != NULL) current_number++; // If creation was successful, raise a flag.
01888   } while (--total);
01889 
01890   if (current_number != 0) return true;
01891 
01892   /* If current_number is still zero at this point, it means that not a single town has been created.
01893    * So give it a last try, but now more aggressive */
01894   if (GenerateTownName(&townnameparts) &&
01895       CreateRandomTown(10000, townnameparts, TSZ_RANDOM, _settings_game.economy.larger_towns != 0, layout) != NULL) {
01896     return true;
01897   }
01898 
01899   /* If there are no towns at all and we are generating new game, bail out */
01900   if (Town::GetNumItems() == 0 && _game_mode != GM_EDITOR) {
01901     ShowErrorMessage(STR_ERROR_COULD_NOT_CREATE_TOWN, INVALID_STRING_ID, WL_CRITICAL);
01902   }
01903 
01904   return false;  // we are still without a town? we failed, simply
01905 }
01906 
01907 
01914 HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
01915 {
01916   uint dist = DistanceSquare(tile, t->xy);
01917 
01918   if (t->fund_buildings_months && dist <= 25) return HZB_TOWN_CENTRE;
01919 
01920   HouseZonesBits smallest = HZB_TOWN_EDGE;
01921   for (HouseZonesBits i = HZB_BEGIN; i < HZB_END; i++) {
01922     if (dist < t->cache.squared_town_zone_radius[i]) smallest = i;
01923   }
01924 
01925   return smallest;
01926 }
01927 
01938 static inline void ClearMakeHouseTile(TileIndex tile, Town *t, byte counter, byte stage, HouseID type, byte random_bits)
01939 {
01940   CommandCost cc = DoCommand(tile, 0, 0, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR);
01941 
01942   assert(cc.Succeeded());
01943 
01944   IncreaseBuildingCount(t, type);
01945   MakeHouseTile(tile, t->index, counter, stage, type, random_bits);
01946   if (HouseSpec::Get(type)->building_flags & BUILDING_IS_ANIMATED) AddAnimatedTile(tile);
01947 
01948   MarkTileDirtyByTile(tile);
01949 }
01950 
01951 
01962 static void MakeTownHouse(TileIndex t, Town *town, byte counter, byte stage, HouseID type, byte random_bits)
01963 {
01964   BuildingFlags size = HouseSpec::Get(type)->building_flags;
01965 
01966   ClearMakeHouseTile(t, town, counter, stage, type, random_bits);
01967   if (size & BUILDING_2_TILES_Y)   ClearMakeHouseTile(t + TileDiffXY(0, 1), town, counter, stage, ++type, random_bits);
01968   if (size & BUILDING_2_TILES_X)   ClearMakeHouseTile(t + TileDiffXY(1, 0), town, counter, stage, ++type, random_bits);
01969   if (size & BUILDING_HAS_4_TILES) ClearMakeHouseTile(t + TileDiffXY(1, 1), town, counter, stage, ++type, random_bits);
01970 }
01971 
01972 
01981 static inline bool CanBuildHouseHere(TileIndex tile, TownID town, bool noslope)
01982 {
01983   /* cannot build on these slopes... */
01984   Slope slope = GetTileSlope(tile);
01985   if ((noslope && slope != SLOPE_FLAT) || IsSteepSlope(slope)) return false;
01986 
01987   /* building under a bridge? */
01988   if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return false;
01989 
01990   /* do not try to build over house owned by another town */
01991   if (IsTileType(tile, MP_HOUSE) && GetTownIndex(tile) != town) return false;
01992 
01993   /* can we clear the land? */
01994   return DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded();
01995 }
01996 
01997 
02007 static inline bool CheckBuildHouseSameZ(TileIndex tile, TownID town, int z, bool noslope)
02008 {
02009   if (!CanBuildHouseHere(tile, town, noslope)) return false;
02010 
02011   /* if building on slopes is allowed, there will be flattening foundation (to tile max z) */
02012   if (GetTileMaxZ(tile) != z) return false;
02013 
02014   return true;
02015 }
02016 
02017 
02027 static bool CheckFree2x2Area(TileIndex tile, TownID town, int z, bool noslope)
02028 {
02029   /* we need to check this tile too because we can be at different tile now */
02030   if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
02031 
02032   for (DiagDirection d = DIAGDIR_SE; d < DIAGDIR_END; d++) {
02033     tile += TileOffsByDiagDir(d);
02034     if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
02035   }
02036 
02037   return true;
02038 }
02039 
02040 
02048 static inline bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile)
02049 {
02050   /* Allow towns everywhere when we don't build roads */
02051   if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
02052 
02053   TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
02054 
02055   switch (t->layout) {
02056     case TL_2X2_GRID:
02057       if ((grid_pos.x % 3) == 0 || (grid_pos.y % 3) == 0) return false;
02058       break;
02059 
02060     case TL_3X3_GRID:
02061       if ((grid_pos.x % 4) == 0 || (grid_pos.y % 4) == 0) return false;
02062       break;
02063 
02064     default:
02065       break;
02066   }
02067 
02068   return true;
02069 }
02070 
02071 
02079 static inline bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile)
02080 {
02081   /* Allow towns everywhere when we don't build roads */
02082   if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
02083 
02084   /* Compute relative position of tile. (Positive offsets are towards north) */
02085   TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
02086 
02087   switch (t->layout) {
02088     case TL_2X2_GRID:
02089       grid_pos.x %= 3;
02090       grid_pos.y %= 3;
02091       if ((grid_pos.x != 2 && grid_pos.x != -1) ||
02092         (grid_pos.y != 2 && grid_pos.y != -1)) return false;
02093       break;
02094 
02095     case TL_3X3_GRID:
02096       if ((grid_pos.x & 3) < 2 || (grid_pos.y & 3) < 2) return false;
02097       break;
02098 
02099     default:
02100       break;
02101   }
02102 
02103   return true;
02104 }
02105 
02106 
02116 static bool CheckTownBuild2House(TileIndex *tile, Town *t, int maxz, bool noslope, DiagDirection second)
02117 {
02118   /* 'tile' is already checked in BuildTownHouse() - CanBuildHouseHere() and slope test */
02119 
02120   TileIndex tile2 = *tile + TileOffsByDiagDir(second);
02121   if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) return true;
02122 
02123   tile2 = *tile + TileOffsByDiagDir(ReverseDiagDir(second));
02124   if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) {
02125     *tile = tile2;
02126     return true;
02127   }
02128 
02129   return false;
02130 }
02131 
02132 
02141 static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, int maxz, bool noslope)
02142 {
02143   TileIndex tile2 = *tile;
02144 
02145   for (DiagDirection d = DIAGDIR_SE;; d++) { // 'd' goes through DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_END
02146     if (TownLayoutAllows2x2HouseHere(t, tile2) && CheckFree2x2Area(tile2, t->index, maxz, noslope)) {
02147       *tile = tile2;
02148       return true;
02149     }
02150     if (d == DIAGDIR_END) break;
02151     tile2 += TileOffsByDiagDir(ReverseDiagDir(d)); // go clockwise
02152   }
02153 
02154   return false;
02155 }
02156 
02157 
02164 static bool BuildTownHouse(Town *t, TileIndex tile)
02165 {
02166   /* forbidden building here by town layout */
02167   if (!TownLayoutAllowsHouseHere(t, tile)) return false;
02168 
02169   /* no house allowed at all, bail out */
02170   if (!CanBuildHouseHere(tile, t->index, false)) return false;
02171 
02172   Slope slope = GetTileSlope(tile);
02173   int maxz = GetTileMaxZ(tile);
02174 
02175   /* Get the town zone type of the current tile, as well as the climate.
02176    * This will allow to easily compare with the specs of the new house to build */
02177   HouseZonesBits rad = GetTownRadiusGroup(t, tile);
02178 
02179   /* Above snow? */
02180   int land = _settings_game.game_creation.landscape;
02181   if (land == LT_ARCTIC && maxz > HighestSnowLine()) land = -1;
02182 
02183   uint bitmask = (1 << rad) + (1 << (land + 12));
02184 
02185   /* bits 0-4 are used
02186    * bits 11-15 are used
02187    * bits 5-10 are not used. */
02188   HouseID houses[HOUSE_MAX];
02189   uint num = 0;
02190   uint probs[HOUSE_MAX];
02191   uint probability_max = 0;
02192 
02193   /* Generate a list of all possible houses that can be built. */
02194   for (uint i = 0; i < HOUSE_MAX; i++) {
02195     const HouseSpec *hs = HouseSpec::Get(i);
02196 
02197     /* Verify that the candidate house spec matches the current tile status */
02198     if ((~hs->building_availability & bitmask) != 0 || !hs->enabled || hs->grf_prop.override != INVALID_HOUSE_ID) continue;
02199 
02200     /* Don't let these counters overflow. Global counters are 32bit, there will never be that many houses. */
02201     if (hs->class_id != HOUSE_NO_CLASS) {
02202       /* id_count is always <= class_count, so it doesn't need to be checked */
02203       if (t->cache.building_counts.class_count[hs->class_id] == UINT16_MAX) continue;
02204     } else {
02205       /* If the house has no class, check id_count instead */
02206       if (t->cache.building_counts.id_count[i] == UINT16_MAX) continue;
02207     }
02208 
02209     /* Without NewHouses, all houses have probability '1' */
02210     uint cur_prob = (_loaded_newgrf_features.has_newhouses ? hs->probability : 1);
02211     probability_max += cur_prob;
02212     probs[num] = cur_prob;
02213     houses[num++] = (HouseID)i;
02214   }
02215 
02216   TileIndex baseTile = tile;
02217 
02218   while (probability_max > 0) {
02219     /* Building a multitile building can change the location of tile.
02220      * The building would still be built partially on that tile, but
02221      * its nothern tile would be elsewere. However, if the callback
02222      * fails we would be basing further work from the changed tile.
02223      * So a next 1x1 tile building could be built on the wrong tile. */
02224     tile = baseTile;
02225 
02226     uint r = RandomRange(probability_max);
02227     uint i;
02228     for (i = 0; i < num; i++) {
02229       if (probs[i] > r) break;
02230       r -= probs[i];
02231     }
02232 
02233     HouseID house = houses[i];
02234     probability_max -= probs[i];
02235 
02236     /* remove tested house from the set */
02237     num--;
02238     houses[i] = houses[num];
02239     probs[i] = probs[num];
02240 
02241     const HouseSpec *hs = HouseSpec::Get(house);
02242 
02243     if (_loaded_newgrf_features.has_newhouses && !_generating_world &&
02244         _game_mode != GM_EDITOR && (hs->extra_flags & BUILDING_IS_HISTORICAL) != 0) {
02245       continue;
02246     }
02247 
02248     if (_cur_year < hs->min_year || _cur_year > hs->max_year) continue;
02249 
02250     /* Special houses that there can be only one of. */
02251     uint oneof = 0;
02252 
02253     if (hs->building_flags & BUILDING_IS_CHURCH) {
02254       SetBit(oneof, TOWN_HAS_CHURCH);
02255     } else if (hs->building_flags & BUILDING_IS_STADIUM) {
02256       SetBit(oneof, TOWN_HAS_STADIUM);
02257     }
02258 
02259     if (t->flags & oneof) continue;
02260 
02261     /* Make sure there is no slope? */
02262     bool noslope = (hs->building_flags & TILE_NOT_SLOPED) != 0;
02263     if (noslope && slope != SLOPE_FLAT) continue;
02264 
02265     if (hs->building_flags & TILE_SIZE_2x2) {
02266       if (!CheckTownBuild2x2House(&tile, t, maxz, noslope)) continue;
02267     } else if (hs->building_flags & TILE_SIZE_2x1) {
02268       if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SW)) continue;
02269     } else if (hs->building_flags & TILE_SIZE_1x2) {
02270       if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SE)) continue;
02271     } else {
02272       /* 1x1 house checks are already done */
02273     }
02274 
02275     byte random_bits = Random();
02276 
02277     if (HasBit(hs->callback_mask, CBM_HOUSE_ALLOW_CONSTRUCTION)) {
02278       uint16 callback_res = GetHouseCallback(CBID_HOUSE_ALLOW_CONSTRUCTION, 0, 0, house, t, tile, true, random_bits);
02279       if (callback_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_ALLOW_CONSTRUCTION, callback_res)) continue;
02280     }
02281 
02282     /* build the house */
02283     t->cache.num_houses++;
02284 
02285     /* Special houses that there can be only one of. */
02286     t->flags |= oneof;
02287 
02288     byte construction_counter = 0;
02289     byte construction_stage = 0;
02290 
02291     if (_generating_world || _game_mode == GM_EDITOR) {
02292       uint32 r = Random();
02293 
02294       construction_stage = TOWN_HOUSE_COMPLETED;
02295       if (Chance16(1, 7)) construction_stage = GB(r, 0, 2);
02296 
02297       if (construction_stage == TOWN_HOUSE_COMPLETED) {
02298         ChangePopulation(t, hs->population);
02299       } else {
02300         construction_counter = GB(r, 2, 2);
02301       }
02302     }
02303 
02304     MakeTownHouse(tile, t, construction_counter, construction_stage, house, random_bits);
02305     UpdateTownRadius(t);
02306     UpdateTownCargoes(t, tile);
02307 
02308     return true;
02309   }
02310 
02311   return false;
02312 }
02313 
02320 static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
02321 {
02322   assert(IsTileType(tile, MP_HOUSE));
02323   DecreaseBuildingCount(t, house);
02324   DoClearSquare(tile);
02325   DeleteAnimatedTile(tile);
02326 
02327   DeleteNewGRFInspectWindow(GSF_HOUSES, tile);
02328 }
02329 
02337 TileIndexDiff GetHouseNorthPart(HouseID &house)
02338 {
02339   if (house >= 3) { // house id 0,1,2 MUST be single tile houses, or this code breaks.
02340     if (HouseSpec::Get(house - 1)->building_flags & TILE_SIZE_2x1) {
02341       house--;
02342       return TileDiffXY(-1, 0);
02343     } else if (HouseSpec::Get(house - 1)->building_flags & BUILDING_2_TILES_Y) {
02344       house--;
02345       return TileDiffXY(0, -1);
02346     } else if (HouseSpec::Get(house - 2)->building_flags & BUILDING_HAS_4_TILES) {
02347       house -= 2;
02348       return TileDiffXY(-1, 0);
02349     } else if (HouseSpec::Get(house - 3)->building_flags & BUILDING_HAS_4_TILES) {
02350       house -= 3;
02351       return TileDiffXY(-1, -1);
02352     }
02353   }
02354   return 0;
02355 }
02356 
02357 void ClearTownHouse(Town *t, TileIndex tile)
02358 {
02359   assert(IsTileType(tile, MP_HOUSE));
02360 
02361   HouseID house = GetHouseType(tile);
02362 
02363   /* need to align the tile to point to the upper left corner of the house */
02364   tile += GetHouseNorthPart(house); // modifies house to the ID of the north tile
02365 
02366   const HouseSpec *hs = HouseSpec::Get(house);
02367 
02368   /* Remove population from the town if the house is finished. */
02369   if (IsHouseCompleted(tile)) {
02370     ChangePopulation(t, -hs->population);
02371   }
02372 
02373   t->cache.num_houses--;
02374 
02375   /* Clear flags for houses that only may exist once/town. */
02376   if (hs->building_flags & BUILDING_IS_CHURCH) {
02377     ClrBit(t->flags, TOWN_HAS_CHURCH);
02378   } else if (hs->building_flags & BUILDING_IS_STADIUM) {
02379     ClrBit(t->flags, TOWN_HAS_STADIUM);
02380   }
02381 
02382   /* Do the actual clearing of tiles */
02383   uint eflags = hs->building_flags;
02384   DoClearTownHouseHelper(tile, t, house);
02385   if (eflags & BUILDING_2_TILES_Y)   DoClearTownHouseHelper(tile + TileDiffXY(0, 1), t, ++house);
02386   if (eflags & BUILDING_2_TILES_X)   DoClearTownHouseHelper(tile + TileDiffXY(1, 0), t, ++house);
02387   if (eflags & BUILDING_HAS_4_TILES) DoClearTownHouseHelper(tile + TileDiffXY(1, 1), t, ++house);
02388 
02389   UpdateTownRadius(t);
02390 
02391   /* Update cargo acceptance. */
02392   UpdateTownCargoes(t, tile);
02393 }
02394 
02404 CommandCost CmdRenameTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02405 {
02406   Town *t = Town::GetIfValid(p1);
02407   if (t == NULL) return CMD_ERROR;
02408 
02409   bool reset = StrEmpty(text);
02410 
02411   if (!reset) {
02412     if (Utf8StringLength(text) >= MAX_LENGTH_TOWN_NAME_CHARS) return CMD_ERROR;
02413     if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
02414   }
02415 
02416   if (flags & DC_EXEC) {
02417     free(t->name);
02418     t->name = reset ? NULL : strdup(text);
02419 
02420     t->UpdateVirtCoord();
02421     InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
02422     UpdateAllStationVirtCoords();
02423   }
02424   return CommandCost();
02425 }
02426 
02432 const CargoSpec *FindFirstCargoWithTownEffect(TownEffect effect)
02433 {
02434   const CargoSpec *cs;
02435   FOR_ALL_CARGOSPECS(cs) {
02436     if (cs->town_effect == effect) return cs;
02437   }
02438   return NULL;
02439 }
02440 
02441 static void UpdateTownGrowRate(Town *t);
02442 
02454 CommandCost CmdTownCargoGoal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02455 {
02456   if (_current_company != OWNER_DEITY) return CMD_ERROR;
02457 
02458   TownEffect te = (TownEffect)GB(p1, 16, 8);
02459   if (te < TE_BEGIN || te > TE_END) return CMD_ERROR;
02460 
02461   uint16 index = GB(p1, 0, 16);
02462   Town *t = Town::GetIfValid(index);
02463   if (t == NULL) return CMD_ERROR;
02464 
02465   /* Validate if there is a cargo which is the requested TownEffect */
02466   const CargoSpec *cargo = FindFirstCargoWithTownEffect(te);
02467   if (cargo == NULL) return CMD_ERROR;
02468 
02469   if (flags & DC_EXEC) {
02470     t->goal[te] = p2;
02471     UpdateTownGrowRate(t);
02472     InvalidateWindowData(WC_TOWN_VIEW, index);
02473   }
02474 
02475   return CommandCost();
02476 }
02477 
02487 CommandCost CmdTownSetText(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02488 {
02489   if (_current_company != OWNER_DEITY) return CMD_ERROR;
02490   Town *t = Town::GetIfValid(p1);
02491   if (t == NULL) return CMD_ERROR;
02492 
02493   if (flags & DC_EXEC) {
02494     free(t->text);
02495     t->text = StrEmpty(text) ? NULL : strdup(text);
02496     InvalidateWindowData(WC_TOWN_VIEW, p1);
02497   }
02498 
02499   return CommandCost();
02500 }
02501 
02511 CommandCost CmdTownGrowthRate(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02512 {
02513   if (_current_company != OWNER_DEITY) return CMD_ERROR;
02514   if ((p2 & TOWN_GROW_RATE_CUSTOM) != 0) return CMD_ERROR;
02515   if (GB(p2, 16, 16) != 0) return CMD_ERROR;
02516 
02517   Town *t = Town::GetIfValid(p1);
02518   if (t == NULL) return CMD_ERROR;
02519 
02520   if (flags & DC_EXEC) {
02521     t->growth_rate = (p2 == 0) ? 0 : p2 | TOWN_GROW_RATE_CUSTOM;
02522     UpdateTownGrowRate(t);
02523     InvalidateWindowData(WC_TOWN_VIEW, p1);
02524   }
02525 
02526   return CommandCost();
02527 }
02528 
02538 CommandCost CmdExpandTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02539 {
02540   if (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY) return CMD_ERROR;
02541   Town *t = Town::GetIfValid(p1);
02542   if (t == NULL) return CMD_ERROR;
02543 
02544   if (flags & DC_EXEC) {
02545     /* The more houses, the faster we grow */
02546     if (p2 == 0) {
02547       uint amount = RandomRange(ClampToU16(t->cache.num_houses / 10)) + 3;
02548       t->cache.num_houses += amount;
02549       UpdateTownRadius(t);
02550 
02551       uint n = amount * 10;
02552       do GrowTown(t); while (--n);
02553 
02554       t->cache.num_houses -= amount;
02555     } else {
02556       for (; p2 > 0; p2--) {
02557         /* Try several times to grow, as we are really suppose to grow */
02558         for (uint i = 0; i < 25; i++) if (GrowTown(t)) break;
02559       }
02560     }
02561     UpdateTownRadius(t);
02562 
02563     UpdateTownMaxPass(t);
02564   }
02565 
02566   return CommandCost();
02567 }
02568 
02578 CommandCost CmdDeleteTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02579 {
02580   if (_game_mode != GM_EDITOR && !_generating_world) return CMD_ERROR;
02581   Town *t = Town::GetIfValid(p1);
02582   if (t == NULL) return CMD_ERROR;
02583 
02584   /* Stations refer to towns. */
02585   const Station *st;
02586   FOR_ALL_STATIONS(st) {
02587     if (st->town == t) {
02588       /* Non-oil rig stations are always a problem. */
02589       if (!(st->facilities & FACIL_AIRPORT) || st->airport.type != AT_OILRIG) return CMD_ERROR;
02590       /* We can only automatically delete oil rigs *if* there's no vehicle on them. */
02591       CommandCost ret = DoCommand(st->airport.tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02592       if (ret.Failed()) return ret;
02593     }
02594   }
02595 
02596   /* Depots refer to towns. */
02597   const Depot *d;
02598   FOR_ALL_DEPOTS(d) {
02599     if (d->town == t) return CMD_ERROR;
02600   }
02601 
02602   /* Check all tiles for town ownership. */
02603   for (TileIndex tile = 0; tile < MapSize(); ++tile) {
02604     bool try_clear = false;
02605     switch (GetTileType(tile)) {
02606       case MP_ROAD:
02607         try_clear = HasTownOwnedRoad(tile) && GetTownIndex(tile) == t->index;
02608         break;
02609 
02610       case MP_TUNNELBRIDGE:
02611         try_clear = IsTileOwner(tile, OWNER_TOWN) && ClosestTownFromTile(tile, UINT_MAX) == t;
02612         break;
02613 
02614       case MP_HOUSE:
02615         try_clear = GetTownIndex(tile) == t->index;
02616         break;
02617 
02618       case MP_INDUSTRY:
02619         try_clear = Industry::GetByTile(tile)->town == t;
02620         break;
02621 
02622       case MP_OBJECT:
02623         if (Town::GetNumItems() == 1) {
02624           /* No towns will be left, remove it! */
02625           try_clear = true;
02626         } else {
02627           Object *o = Object::GetByTile(tile);
02628           if (o->town == t) {
02629             if (GetObjectType(tile) == OBJECT_STATUE) {
02630               /* Statue... always remove. */
02631               try_clear = true;
02632             } else {
02633               /* Tell to find a new town. */
02634               if (flags & DC_EXEC) o->town = NULL;
02635             }
02636           }
02637         }
02638         break;
02639 
02640       default:
02641         break;
02642     }
02643     if (try_clear) {
02644       CommandCost ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02645       if (ret.Failed()) return ret;
02646     }
02647   }
02648 
02649   /* The town destructor will delete the other things related to the town. */
02650   if (flags & DC_EXEC) delete t;
02651 
02652   return CommandCost();
02653 }
02654 
02659 const byte _town_action_costs[TACT_COUNT] = {
02660   2, 4, 9, 35, 48, 53, 117, 175
02661 };
02662 
02663 static CommandCost TownActionAdvertiseSmall(Town *t, DoCommandFlag flags)
02664 {
02665   if (flags & DC_EXEC) {
02666     ModifyStationRatingAround(t->xy, _current_company, 0x40, 10);
02667   }
02668   return CommandCost();
02669 }
02670 
02671 static CommandCost TownActionAdvertiseMedium(Town *t, DoCommandFlag flags)
02672 {
02673   if (flags & DC_EXEC) {
02674     ModifyStationRatingAround(t->xy, _current_company, 0x70, 15);
02675   }
02676   return CommandCost();
02677 }
02678 
02679 static CommandCost TownActionAdvertiseLarge(Town *t, DoCommandFlag flags)
02680 {
02681   if (flags & DC_EXEC) {
02682     ModifyStationRatingAround(t->xy, _current_company, 0xA0, 20);
02683   }
02684   return CommandCost();
02685 }
02686 
02687 static CommandCost TownActionRoadRebuild(Town *t, DoCommandFlag flags)
02688 {
02689   /* Check if the company is allowed to fund new roads. */
02690   if (!_settings_game.economy.fund_roads) return CMD_ERROR;
02691 
02692   if (flags & DC_EXEC) {
02693     t->road_build_months = 6;
02694 
02695     char company_name[MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH];
02696     SetDParam(0, _current_company);
02697     GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
02698 
02699     char *cn = strdup(company_name);
02700     SetDParam(0, t->index);
02701     SetDParamStr(1, cn);
02702 
02703     AddNewsItem(STR_NEWS_ROAD_REBUILDING, NS_GENERAL, NR_TOWN, t->index, NR_NONE, UINT32_MAX, cn);
02704   }
02705   return CommandCost();
02706 }
02707 
02713 static bool TryClearTile(TileIndex tile)
02714 {
02715   Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
02716   CommandCost r = DoCommand(tile, 0, 0, DC_NONE, CMD_LANDSCAPE_CLEAR);
02717   cur_company.Restore();
02718   return r.Succeeded();
02719 }
02720 
02722 struct StatueBuildSearchData {
02723   TileIndex best_position; 
02724   int tile_count;          
02725 
02726   StatueBuildSearchData(TileIndex best_pos, int count) : best_position(best_pos), tile_count(count) { }
02727 };
02728 
02735 static bool SearchTileForStatue(TileIndex tile, void *user_data)
02736 {
02737   static const int STATUE_NUMBER_INNER_TILES = 25; // Number of tiles int the center of the city, where we try to protect houses.
02738 
02739   StatueBuildSearchData *statue_data = (StatueBuildSearchData *)user_data;
02740   statue_data->tile_count++;
02741 
02742   /* Statues can be build on slopes, just like houses. Only the steep slopes is a no go. */
02743   if (IsSteepSlope(GetTileSlope(tile))) return false;
02744   /* Don't build statues under bridges. */
02745   if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return false;
02746 
02747   /* A clear-able open space is always preferred. */
02748   if ((IsTileType(tile, MP_CLEAR) || IsTileType(tile, MP_TREES)) && TryClearTile(tile)) {
02749     statue_data->best_position = tile;
02750     return true;
02751   }
02752 
02753   bool house = IsTileType(tile, MP_HOUSE);
02754 
02755   /* Searching inside the inner circle. */
02756   if (statue_data->tile_count <= STATUE_NUMBER_INNER_TILES) {
02757     /* Save first house in inner circle. */
02758     if (house && statue_data->best_position == INVALID_TILE && TryClearTile(tile)) {
02759       statue_data->best_position = tile;
02760     }
02761 
02762     /* If we have reached the end of the inner circle, and have a saved house, terminate the search. */
02763     return statue_data->tile_count == STATUE_NUMBER_INNER_TILES && statue_data->best_position != INVALID_TILE;
02764   }
02765 
02766   /* Searching outside the circle, just pick the first possible spot. */
02767   statue_data->best_position = tile; // Is optimistic, the condition below must also hold.
02768   return house && TryClearTile(tile);
02769 }
02770 
02778 static CommandCost TownActionBuildStatue(Town *t, DoCommandFlag flags)
02779 {
02780   if (!Object::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_OBJECTS);
02781 
02782   TileIndex tile = t->xy;
02783   StatueBuildSearchData statue_data(INVALID_TILE, 0);
02784   if (!CircularTileSearch(&tile, 9, SearchTileForStatue, &statue_data)) return_cmd_error(STR_ERROR_STATUE_NO_SUITABLE_PLACE);
02785 
02786   if (flags & DC_EXEC) {
02787     Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
02788     DoCommand(statue_data.best_position, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
02789     cur_company.Restore();
02790     BuildObject(OBJECT_STATUE, statue_data.best_position, _current_company, t);
02791     SetBit(t->statues, _current_company); // Once found and built, "inform" the Town.
02792     MarkTileDirtyByTile(statue_data.best_position);
02793   }
02794   return CommandCost();
02795 }
02796 
02797 static CommandCost TownActionFundBuildings(Town *t, DoCommandFlag flags)
02798 {
02799   /* Check if it's allowed to buy the rights */
02800   if (!_settings_game.economy.fund_buildings) return CMD_ERROR;
02801 
02802   if (flags & DC_EXEC) {
02803     /* Build next tick */
02804     t->grow_counter = 1;
02805     /* If we were not already growing */
02806     SetBit(t->flags, TOWN_IS_FUNDED);
02807     /* And grow for 3 months */
02808     t->fund_buildings_months = 3;
02809 
02810     SetWindowDirty(WC_TOWN_VIEW, t->index);
02811   }
02812   return CommandCost();
02813 }
02814 
02815 static CommandCost TownActionBuyRights(Town *t, DoCommandFlag flags)
02816 {
02817   /* Check if it's allowed to buy the rights */
02818   if (!_settings_game.economy.exclusive_rights) return CMD_ERROR;
02819 
02820   if (flags & DC_EXEC) {
02821     t->exclusive_counter = 12;
02822     t->exclusivity = _current_company;
02823 
02824     ModifyStationRatingAround(t->xy, _current_company, 130, 17);
02825   }
02826   return CommandCost();
02827 }
02828 
02829 static CommandCost TownActionBribe(Town *t, DoCommandFlag flags)
02830 {
02831   if (flags & DC_EXEC) {
02832     if (Chance16(1, 14)) {
02833       /* set as unwanted for 6 months */
02834       t->unwanted[_current_company] = 6;
02835 
02836       /* set all close by station ratings to 0 */
02837       Station *st;
02838       FOR_ALL_STATIONS(st) {
02839         if (st->town == t && st->owner == _current_company) {
02840           for (CargoID i = 0; i < NUM_CARGO; i++) st->goods[i].rating = 0;
02841         }
02842       }
02843 
02844       /* only show errormessage to the executing player. All errors are handled command.c
02845        * but this is special, because it can only 'fail' on a DC_EXEC */
02846       if (IsLocalCompany()) ShowErrorMessage(STR_ERROR_BRIBE_FAILED, INVALID_STRING_ID, WL_INFO);
02847 
02848       /* decrease by a lot!
02849        * ChangeTownRating is only for stuff in demolishing. Bribe failure should
02850        * be independent of any cheat settings
02851        */
02852       if (t->ratings[_current_company] > RATING_BRIBE_DOWN_TO) {
02853         t->ratings[_current_company] = RATING_BRIBE_DOWN_TO;
02854         SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
02855       }
02856     } else {
02857       ChangeTownRating(t, RATING_BRIBE_UP_STEP, RATING_BRIBE_MAXIMUM, DC_EXEC);
02858     }
02859   }
02860   return CommandCost();
02861 }
02862 
02863 typedef CommandCost TownActionProc(Town *t, DoCommandFlag flags);
02864 static TownActionProc * const _town_action_proc[] = {
02865   TownActionAdvertiseSmall,
02866   TownActionAdvertiseMedium,
02867   TownActionAdvertiseLarge,
02868   TownActionRoadRebuild,
02869   TownActionBuildStatue,
02870   TownActionFundBuildings,
02871   TownActionBuyRights,
02872   TownActionBribe
02873 };
02874 
02882 uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t)
02883 {
02884   int num = 0;
02885   TownActions buttons = TACT_NONE;
02886 
02887   /* Spectators and unwanted have no options */
02888   if (cid != COMPANY_SPECTATOR && !(_settings_game.economy.bribe && t->unwanted[cid])) {
02889 
02890     /* Things worth more than this are not shown */
02891     Money avail = Company::Get(cid)->money + _price[PR_STATION_VALUE] * 200;
02892 
02893     /* Check the action bits for validity and
02894      * if they are valid add them */
02895     for (uint i = 0; i != lengthof(_town_action_costs); i++) {
02896       const TownActions cur = (TownActions)(1 << i);
02897 
02898       /* Is the company not able to bribe ? */
02899       if (cur == TACT_BRIBE && (!_settings_game.economy.bribe || t->ratings[cid] >= RATING_BRIBE_MAXIMUM)) continue;
02900 
02901       /* Is the company not able to buy exclusive rights ? */
02902       if (cur == TACT_BUY_RIGHTS && !_settings_game.economy.exclusive_rights) continue;
02903 
02904       /* Is the company not able to fund buildings ? */
02905       if (cur == TACT_FUND_BUILDINGS && !_settings_game.economy.fund_buildings) continue;
02906 
02907       /* Is the company not able to fund local road reconstruction? */
02908       if (cur == TACT_ROAD_REBUILD && !_settings_game.economy.fund_roads) continue;
02909 
02910       /* Is the company not able to build a statue ? */
02911       if (cur == TACT_BUILD_STATUE && HasBit(t->statues, cid)) continue;
02912 
02913       if (avail >= _town_action_costs[i] * _price[PR_TOWN_ACTION] >> 8) {
02914         buttons |= cur;
02915         num++;
02916       }
02917     }
02918   }
02919 
02920   if (nump != NULL) *nump = num;
02921   return buttons;
02922 }
02923 
02935 CommandCost CmdDoTownAction(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02936 {
02937   Town *t = Town::GetIfValid(p1);
02938   if (t == NULL || p2 >= lengthof(_town_action_proc)) return CMD_ERROR;
02939 
02940   if (!HasBit(GetMaskOfTownActions(NULL, _current_company, t), p2)) return CMD_ERROR;
02941 
02942   CommandCost cost(EXPENSES_OTHER, _price[PR_TOWN_ACTION] * _town_action_costs[p2] >> 8);
02943 
02944   CommandCost ret = _town_action_proc[p2](t, flags);
02945   if (ret.Failed()) return ret;
02946 
02947   if (flags & DC_EXEC) {
02948     SetWindowDirty(WC_TOWN_AUTHORITY, p1);
02949   }
02950 
02951   return cost;
02952 }
02953 
02954 static void UpdateTownRating(Town *t)
02955 {
02956   /* Increase company ratings if they're low */
02957   const Company *c;
02958   FOR_ALL_COMPANIES(c) {
02959     if (t->ratings[c->index] < RATING_GROWTH_MAXIMUM) {
02960       t->ratings[c->index] = min((int)RATING_GROWTH_MAXIMUM, t->ratings[c->index] + RATING_GROWTH_UP_STEP);
02961     }
02962   }
02963 
02964   const Station *st;
02965   FOR_ALL_STATIONS(st) {
02966     if (DistanceSquare(st->xy, t->xy) <= t->cache.squared_town_zone_radius[0]) {
02967       if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
02968         if (Company::IsValidID(st->owner)) {
02969           int new_rating = t->ratings[st->owner] + RATING_STATION_UP_STEP;
02970           t->ratings[st->owner] = min(new_rating, INT16_MAX); // do not let it overflow
02971         }
02972       } else {
02973         if (Company::IsValidID(st->owner)) {
02974           int new_rating = t->ratings[st->owner] + RATING_STATION_DOWN_STEP;
02975           t->ratings[st->owner] = max(new_rating, INT16_MIN);
02976         }
02977       }
02978     }
02979   }
02980 
02981   /* clamp all ratings to valid values */
02982   for (uint i = 0; i < MAX_COMPANIES; i++) {
02983     t->ratings[i] = Clamp(t->ratings[i], RATING_MINIMUM, RATING_MAXIMUM);
02984   }
02985 
02986   SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
02987 }
02988 
02989 static void UpdateTownGrowRate(Town *t)
02990 {
02991   ClrBit(t->flags, TOWN_IS_FUNDED);
02992   SetWindowDirty(WC_TOWN_VIEW, t->index);
02993 
02994   if (_settings_game.economy.town_growth_rate == 0 && t->fund_buildings_months == 0) return;
02995 
02996   if (t->fund_buildings_months == 0) {
02997     /* Check if all goals are reached for this town to grow (given we are not funding it) */
02998     for (int i = TE_BEGIN; i < TE_END; i++) {
02999       switch (t->goal[i]) {
03000         case TOWN_GROWTH_WINTER:
03001           if (TileHeight(t->xy) >= GetSnowLine() && t->received[i].old_act == 0 && t->cache.population > 90) return;
03002           break;
03003         case TOWN_GROWTH_DESERT:
03004           if (GetTropicZone(t->xy) == TROPICZONE_DESERT && t->received[i].old_act == 0 && t->cache.population > 60) return;
03005           break;
03006         default:
03007           if (t->goal[i] > t->received[i].old_act) return;
03008           break;
03009       }
03010     }
03011   }
03012 
03013   if ((t->growth_rate & TOWN_GROW_RATE_CUSTOM) != 0) {
03014     SetBit(t->flags, TOWN_IS_FUNDED);
03015     SetWindowDirty(WC_TOWN_VIEW, t->index);
03016     return;
03017   }
03018 
03023   static const uint16 _grow_count_values[2][6] = {
03024     { 120, 120, 120, 100,  80,  60 }, // Fund new buildings has been activated
03025     { 320, 420, 300, 220, 160, 100 }  // Normal values
03026   };
03027 
03028   int n = 0;
03029 
03030   const Station *st;
03031   FOR_ALL_STATIONS(st) {
03032     if (DistanceSquare(st->xy, t->xy) <= t->cache.squared_town_zone_radius[0]) {
03033       if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
03034         n++;
03035       }
03036     }
03037   }
03038 
03039   uint16 m;
03040 
03041   if (t->fund_buildings_months != 0) {
03042     m = _grow_count_values[0][min(n, 5)];
03043   } else {
03044     m = _grow_count_values[1][min(n, 5)];
03045     if (n == 0 && !Chance16(1, 12)) return;
03046   }
03047 
03048   /* Use the normal growth rate values if new buildings have been funded in
03049    * this town and the growth rate is set to none. */
03050   uint growth_multiplier = _settings_game.economy.town_growth_rate != 0 ? _settings_game.economy.town_growth_rate - 1 : 1;
03051 
03052   m >>= growth_multiplier;
03053   if (t->larger_town) m /= 2;
03054 
03055   t->growth_rate = m / (t->cache.num_houses / 50 + 1);
03056   if (m <= t->grow_counter) {
03057     t->grow_counter = m;
03058   }
03059 
03060   SetBit(t->flags, TOWN_IS_FUNDED);
03061   SetWindowDirty(WC_TOWN_VIEW, t->index);
03062 }
03063 
03064 static void UpdateTownAmounts(Town *t)
03065 {
03066   for (CargoID i = 0; i < NUM_CARGO; i++) t->supplied[i].NewMonth();
03067   for (int i = TE_BEGIN; i < TE_END; i++) t->received[i].NewMonth();
03068   if (t->fund_buildings_months != 0) t->fund_buildings_months--;
03069 
03070   SetWindowDirty(WC_TOWN_VIEW, t->index);
03071 }
03072 
03073 static void UpdateTownUnwanted(Town *t)
03074 {
03075   const Company *c;
03076 
03077   FOR_ALL_COMPANIES(c) {
03078     if (t->unwanted[c->index] > 0) t->unwanted[c->index]--;
03079   }
03080 }
03081 
03088 CommandCost CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags)
03089 {
03090   if (!Company::IsValidID(_current_company) || (flags & DC_NO_TEST_TOWN_RATING)) return CommandCost();
03091 
03092   Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
03093   if (t == NULL) return CommandCost();
03094 
03095   if (t->ratings[_current_company] > RATING_VERYPOOR) return CommandCost();
03096 
03097   SetDParam(0, t->index);
03098   return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
03099 }
03100 
03109 Town *CalcClosestTownFromTile(TileIndex tile, uint threshold)
03110 {
03111   Town *t;
03112   uint best = threshold;
03113   Town *best_town = NULL;
03114 
03115   FOR_ALL_TOWNS(t) {
03116     uint dist = DistanceManhattan(tile, t->xy);
03117     if (dist < best) {
03118       best = dist;
03119       best_town = t;
03120     }
03121   }
03122 
03123   return best_town;
03124 }
03125 
03134 Town *ClosestTownFromTile(TileIndex tile, uint threshold)
03135 {
03136   switch (GetTileType(tile)) {
03137     case MP_ROAD:
03138       if (IsRoadDepot(tile)) return CalcClosestTownFromTile(tile, threshold);
03139 
03140       if (!HasTownOwnedRoad(tile)) {
03141         TownID tid = GetTownIndex(tile);
03142 
03143         if (tid == (TownID)INVALID_TOWN) {
03144           /* in the case we are generating "many random towns", this value may be INVALID_TOWN */
03145           if (_generating_world) return CalcClosestTownFromTile(tile, threshold);
03146           assert(Town::GetNumItems() == 0);
03147           return NULL;
03148         }
03149 
03150         assert(Town::IsValidID(tid));
03151         Town *town = Town::Get(tid);
03152 
03153         if (DistanceManhattan(tile, town->xy) >= threshold) town = NULL;
03154 
03155         return town;
03156       }
03157       /* FALL THROUGH */
03158 
03159     case MP_HOUSE:
03160       return Town::GetByTile(tile);
03161 
03162     default:
03163       return CalcClosestTownFromTile(tile, threshold);
03164   }
03165 }
03166 
03167 static bool _town_rating_test = false; 
03168 static SmallMap<const Town *, int, 4> _town_test_ratings; 
03169 
03175 void SetTownRatingTestMode(bool mode)
03176 {
03177   static int ref_count = 0; // Number of times test-mode is switched on.
03178   if (mode) {
03179     if (ref_count == 0) {
03180       _town_test_ratings.Clear();
03181     }
03182     ref_count++;
03183   } else {
03184     assert(ref_count > 0);
03185     ref_count--;
03186   }
03187   _town_rating_test = !(ref_count == 0);
03188 }
03189 
03195 static int GetRating(const Town *t)
03196 {
03197   if (_town_rating_test) {
03198     SmallMap<const Town *, int>::iterator it = _town_test_ratings.Find(t);
03199     if (it != _town_test_ratings.End()) {
03200       return it->second;
03201     }
03202   }
03203   return t->ratings[_current_company];
03204 }
03205 
03213 void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
03214 {
03215   /* if magic_bulldozer cheat is active, town doesn't penalize for removing stuff */
03216   if (t == NULL || (flags & DC_NO_MODIFY_TOWN_RATING) ||
03217       !Company::IsValidID(_current_company) ||
03218       (_cheats.magic_bulldozer.value && add < 0)) {
03219     return;
03220   }
03221 
03222   int rating = GetRating(t);
03223   if (add < 0) {
03224     if (rating > max) {
03225       rating += add;
03226       if (rating < max) rating = max;
03227     }
03228   } else {
03229     if (rating < max) {
03230       rating += add;
03231       if (rating > max) rating = max;
03232     }
03233   }
03234   if (_town_rating_test) {
03235     _town_test_ratings[t] = rating;
03236   } else {
03237     SetBit(t->have_ratings, _current_company);
03238     t->ratings[_current_company] = rating;
03239     SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
03240   }
03241 }
03242 
03250 CommandCost CheckforTownRating(DoCommandFlag flags, Town *t, TownRatingCheckType type)
03251 {
03252   /* if magic_bulldozer cheat is active, town doesn't restrict your destructive actions */
03253   if (t == NULL || !Company::IsValidID(_current_company) ||
03254       _cheats.magic_bulldozer.value || (flags & DC_NO_TEST_TOWN_RATING)) {
03255     return CommandCost();
03256   }
03257 
03258   /* minimum rating needed to be allowed to remove stuff */
03259   static const int needed_rating[][TOWN_RATING_CHECK_TYPE_COUNT] = {
03260     /*                  ROAD_REMOVE,                    TUNNELBRIDGE_REMOVE */
03261     { RATING_ROAD_NEEDED_PERMISSIVE, RATING_TUNNEL_BRIDGE_NEEDED_PERMISSIVE}, // Permissive
03262     {    RATING_ROAD_NEEDED_NEUTRAL,    RATING_TUNNEL_BRIDGE_NEEDED_NEUTRAL}, // Neutral
03263     {    RATING_ROAD_NEEDED_HOSTILE,    RATING_TUNNEL_BRIDGE_NEEDED_HOSTILE}, // Hostile
03264   };
03265 
03266   /* check if you're allowed to remove the road/bridge/tunnel
03267    * owned by a town no removal if rating is lower than ... depends now on
03268    * difficulty setting. Minimum town rating selected by difficulty level
03269    */
03270   int needed = needed_rating[_settings_game.difficulty.town_council_tolerance][type];
03271 
03272   if (GetRating(t) < needed) {
03273     SetDParam(0, t->index);
03274     return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
03275   }
03276 
03277   return CommandCost();
03278 }
03279 
03280 void TownsMonthlyLoop()
03281 {
03282   Town *t;
03283 
03284   FOR_ALL_TOWNS(t) {
03285     if (t->road_build_months != 0) t->road_build_months--;
03286 
03287     if (t->exclusive_counter != 0) {
03288       if (--t->exclusive_counter == 0) t->exclusivity = INVALID_COMPANY;
03289     }
03290 
03291     UpdateTownAmounts(t);
03292     UpdateTownRating(t);
03293     UpdateTownGrowRate(t);
03294     UpdateTownUnwanted(t);
03295     UpdateTownCargoes(t);
03296   }
03297 
03298   UpdateTownCargoBitmap();
03299 }
03300 
03301 void TownsYearlyLoop()
03302 {
03303   /* Increment house ages */
03304   for (TileIndex t = 0; t < MapSize(); t++) {
03305     if (!IsTileType(t, MP_HOUSE)) continue;
03306     IncrementHouseAge(t);
03307   }
03308 }
03309 
03310 static CommandCost TerraformTile_Town(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
03311 {
03312   if (AutoslopeEnabled()) {
03313     HouseID house = GetHouseType(tile);
03314     GetHouseNorthPart(house); // modifies house to the ID of the north tile
03315     const HouseSpec *hs = HouseSpec::Get(house);
03316 
03317     /* Here we differ from TTDP by checking TILE_NOT_SLOPED */
03318     if (((hs->building_flags & TILE_NOT_SLOPED) == 0) && !IsSteepSlope(tileh_new) &&
03319         (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
03320       bool allow_terraform = true;
03321 
03322       /* Call the autosloping callback per tile, not for the whole building at once. */
03323       house = GetHouseType(tile);
03324       hs = HouseSpec::Get(house);
03325       if (HasBit(hs->callback_mask, CBM_HOUSE_AUTOSLOPE)) {
03326         /* If the callback fails, allow autoslope. */
03327         uint16 res = GetHouseCallback(CBID_HOUSE_AUTOSLOPE, 0, 0, house, Town::GetByTile(tile), tile);
03328         if (res != CALLBACK_FAILED && ConvertBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_AUTOSLOPE, res)) allow_terraform = false;
03329       }
03330 
03331       if (allow_terraform) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
03332     }
03333   }
03334 
03335   return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
03336 }
03337 
03339 extern const TileTypeProcs _tile_type_town_procs = {
03340   DrawTile_Town,           // draw_tile_proc
03341   GetSlopePixelZ_Town,     // get_slope_z_proc
03342   ClearTile_Town,          // clear_tile_proc
03343   AddAcceptedCargo_Town,   // add_accepted_cargo_proc
03344   GetTileDesc_Town,        // get_tile_desc_proc
03345   GetTileTrackStatus_Town, // get_tile_track_status_proc
03346   NULL,                    // click_tile_proc
03347   AnimateTile_Town,        // animate_tile_proc
03348   TileLoop_Town,           // tile_loop_proc
03349   ChangeTileOwner_Town,    // change_tile_owner_proc
03350   AddProducedCargo_Town,   // add_produced_cargo_proc
03351   NULL,                    // vehicle_enter_tile_proc
03352   GetFoundation_Town,      // get_foundation_proc
03353   TerraformTile_Town,      // terraform_tile_proc
03354 };
03355 
03356 
03357 HouseSpec _house_specs[HOUSE_MAX];
03358 
03359 void ResetHouses()
03360 {
03361   memset(&_house_specs, 0, sizeof(_house_specs));
03362   memcpy(&_house_specs, &_original_house_specs, sizeof(_original_house_specs));
03363 
03364   /* Reset any overrides that have been set. */
03365   _house_mngr.ResetOverride();
03366 }