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