town_cmd.cpp

Go to the documentation of this file.
00001 /* $Id: town_cmd.cpp 17629 2009-09-24 19:22:32Z rubidium $ */
00002 
00005 #include "stdafx.h"
00006 #include "openttd.h"
00007 #include "road_type.h"
00008 #include "road_internal.h" /* Cleaning up road bits */
00009 #include "road_cmd.h"
00010 #include "landscape.h"
00011 #include "town_map.h"
00012 #include "viewport_func.h"
00013 #include "command_func.h"
00014 #include "industry.h"
00015 #include "station_base.h"
00016 #include "company_base.h"
00017 #include "news_func.h"
00018 #include "gui.h"
00019 #include "unmovable_map.h"
00020 #include "water_map.h"
00021 #include "variables.h"
00022 #include "slope_func.h"
00023 #include "genworld.h"
00024 #include "newgrf.h"
00025 #include "newgrf_house.h"
00026 #include "newgrf_commons.h"
00027 #include "newgrf_townname.h"
00028 #include "newgrf_text.h"
00029 #include "autoslope.h"
00030 #include "waypoint.h"
00031 #include "transparency.h"
00032 #include "tunnelbridge_map.h"
00033 #include "strings_func.h"
00034 #include "window_func.h"
00035 #include "string_func.h"
00036 #include "newgrf_cargo.h"
00037 #include "oldpool_func.h"
00038 #include "economy_func.h"
00039 #include "station_func.h"
00040 #include "station_map.h"
00041 #include "cheat_type.h"
00042 #include "functions.h"
00043 #include "animated_tile_func.h"
00044 #include "date_func.h"
00045 #include "core/smallmap_type.hpp"
00046 
00047 #include "table/strings.h"
00048 #include "table/town_land.h"
00049 
00050 uint _total_towns;
00051 HouseSpec _house_specs[HOUSE_MAX];
00052 
00053 Town *_cleared_town;
00054 int _cleared_town_rating;
00055 
00056 uint32 _cur_town_ctr;     
00057 uint32 _cur_town_iter;    
00058 
00059 /* Initialize the town-pool */
00060 DEFINE_OLD_POOL_GENERIC(Town, Town)
00061 
00062 Town::Town(TileIndex tile)
00063 {
00064   if (tile != INVALID_TILE) _total_towns++;
00065   this->xy = tile;
00066 }
00067 
00068 Town::~Town()
00069 {
00070   free(this->name);
00071 
00072   if (CleaningPool()) return;
00073 
00074   Industry *i;
00075 
00076   /* Delete town authority window
00077    * and remove from list of sorted towns */
00078   DeleteWindowById(WC_TOWN_VIEW, this->index);
00079   InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
00080   _total_towns--;
00081 
00082   /* Delete all industries belonging to the town */
00083   FOR_ALL_INDUSTRIES(i) if (i->town == this) delete i;
00084 
00085   /* Go through all tiles and delete those belonging to the town */
00086   for (TileIndex tile = 0; tile < MapSize(); ++tile) {
00087     switch (GetTileType(tile)) {
00088       case MP_HOUSE:
00089         if (GetTownByTile(tile) == this) DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
00090         break;
00091 
00092       case MP_ROAD:
00093         /* Cached nearest town is updated later (after this town has been deleted) */
00094         if (HasTownOwnedRoad(tile) && GetTownIndex(tile) == this->index) {
00095           DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
00096         }
00097         break;
00098 
00099       case MP_TUNNELBRIDGE:
00100         if (IsTileOwner(tile, OWNER_TOWN) &&
00101             ClosestTownFromTile(tile, UINT_MAX) == this)
00102           DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
00103         break;
00104 
00105       default:
00106         break;
00107     }
00108   }
00109 
00110   DeleteSubsidyWithTown(this->index);
00111 
00112   MarkWholeScreenDirty();
00113 
00114   this->xy = INVALID_TILE;
00115 
00116   UpdateNearestTownForRoadTiles(false);
00117 }
00118 
00122 void Town::InitializeLayout(TownLayout layout)
00123 {
00124   if (layout != TL_RANDOM) {
00125     this->layout = layout;
00126     return;
00127   }
00128 
00129   this->layout = TileHash(TileX(this->xy), TileY(this->xy)) % (NUM_TLS - 1);
00130 }
00131 
00132 Money HouseSpec::GetRemovalCost() const
00133 {
00134   return (_price.remove_house * this->removal_cost) >> 8;
00135 }
00136 
00137 // Local
00138 static int _grow_town_result;
00139 
00140 /* Describe the possible states */
00141 enum TownGrowthResult {
00142   GROWTH_SUCCEED         = -1,
00143   GROWTH_SEARCH_STOPPED  =  0
00144 //  GROWTH_SEARCH_RUNNING >=  1
00145 };
00146 
00147 static bool BuildTownHouse(Town *t, TileIndex tile);
00148 
00149 static void TownDrawHouseLift(const TileInfo *ti)
00150 {
00151   AddChildSpriteScreen(SPR_LIFT, PAL_NONE, 14, 60 - GetLiftPosition(ti->tile));
00152 }
00153 
00154 typedef void TownDrawTileProc(const TileInfo *ti);
00155 static TownDrawTileProc * const _town_draw_tile_procs[1] = {
00156   TownDrawHouseLift
00157 };
00158 
00164 static inline DiagDirection RandomDiagDir()
00165 {
00166   return (DiagDirection)(3 & Random());
00167 }
00168 
00174 static void DrawTile_Town(TileInfo *ti)
00175 {
00176   HouseID house_id = GetHouseType(ti->tile);
00177 
00178   if (house_id >= NEW_HOUSE_OFFSET) {
00179     /* Houses don't necessarily need new graphics. If they don't have a
00180      * spritegroup associated with them, then the sprite for the substitute
00181      * house id is drawn instead. */
00182     if (GetHouseSpecs(house_id)->spritegroup != NULL) {
00183       DrawNewHouseTile(ti, house_id);
00184       return;
00185     } else {
00186       house_id = GetHouseSpecs(house_id)->substitute_id;
00187     }
00188   }
00189 
00190   /* Retrieve pointer to the draw town tile struct */
00191   const DrawBuildingsTileStruct *dcts = &_town_draw_tile_data[house_id << 4 | TileHash2Bit(ti->x, ti->y) << 2 | GetHouseBuildingStage(ti->tile)];
00192 
00193   if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
00194 
00195   DrawGroundSprite(dcts->ground.sprite, dcts->ground.pal);
00196 
00197   /* If houses are invisible, do not draw the upper part */
00198   if (IsInvisibilitySet(TO_HOUSES)) return;
00199 
00200   /* Add a house on top of the ground? */
00201   SpriteID image = dcts->building.sprite;
00202   if (image != 0) {
00203     AddSortableSpriteToDraw(image, dcts->building.pal,
00204       ti->x + dcts->subtile_x,
00205       ti->y + dcts->subtile_y,
00206       dcts->width,
00207       dcts->height,
00208       dcts->dz,
00209       ti->z,
00210       IsTransparencySet(TO_HOUSES)
00211     );
00212 
00213     if (IsTransparencySet(TO_HOUSES)) return;
00214   }
00215 
00216   {
00217     int proc = dcts->draw_proc - 1;
00218 
00219     if (proc >= 0) _town_draw_tile_procs[proc](ti);
00220   }
00221 }
00222 
00223 static uint GetSlopeZ_Town(TileIndex tile, uint x, uint y)
00224 {
00225   return GetTileMaxZ(tile);
00226 }
00227 
00229 static Foundation GetFoundation_Town(TileIndex tile, Slope tileh)
00230 {
00231   return FlatteningFoundation(tileh);
00232 }
00233 
00240 static void AnimateTile_Town(TileIndex tile)
00241 {
00242   if (GetHouseType(tile) >= NEW_HOUSE_OFFSET) {
00243     AnimateNewHouseTile(tile);
00244     return;
00245   }
00246 
00247   if (_tick_counter & 3) return;
00248 
00249   /* If the house is not one with a lift anymore, then stop this animating.
00250    * Not exactly sure when this happens, but probably when a house changes.
00251    * Before this was just a return...so it'd leak animated tiles..
00252    * That bug seems to have been here since day 1?? */
00253   if (!(GetHouseSpecs(GetHouseType(tile))->building_flags & BUILDING_IS_ANIMATED)) {
00254     DeleteAnimatedTile(tile);
00255     return;
00256   }
00257 
00258   if (!LiftHasDestination(tile)) {
00259     uint i;
00260 
00261     /* Building has 6 floors, number 0 .. 6, where 1 is illegal.
00262      * This is due to the fact that the first floor is, in the graphics,
00263      *  the height of 2 'normal' floors.
00264      * Furthermore, there are 6 lift positions from floor N (incl) to floor N + 1 (excl) */
00265     do {
00266       i = RandomRange(7);
00267     } while (i == 1 || i * 6 == GetLiftPosition(tile));
00268 
00269     SetLiftDestination(tile, i);
00270   }
00271 
00272   int pos = GetLiftPosition(tile);
00273   int dest = GetLiftDestination(tile) * 6;
00274   pos += (pos < dest) ? 1 : -1;
00275   SetLiftPosition(tile, pos);
00276 
00277   if (pos == dest) {
00278     HaltLift(tile);
00279     DeleteAnimatedTile(tile);
00280   }
00281 
00282   MarkTileDirtyByTile(tile);
00283 }
00284 
00291 static bool IsCloseToTown(TileIndex tile, uint dist)
00292 {
00293   const Town *t;
00294 
00295   FOR_ALL_TOWNS(t) {
00296     if (DistanceManhattan(tile, t->xy) < dist) return true;
00297   }
00298   return false;
00299 }
00300 
00309 static void MarkTownSignDirty(Town *t)
00310 {
00311   MarkAllViewportsDirty(
00312     t->sign.left - 6,
00313     t->sign.top - 3,
00314     t->sign.left + t->sign.width_1 * 4 + 12,
00315     t->sign.top + 45
00316   );
00317 }
00318 
00324 void UpdateTownVirtCoord(Town *t)
00325 {
00326   MarkTownSignDirty(t);
00327   Point pt = RemapCoords2(TileX(t->xy) * TILE_SIZE, TileY(t->xy) * TILE_SIZE);
00328   SetDParam(0, t->index);
00329   SetDParam(1, t->population);
00330   UpdateViewportSignPos(&t->sign, pt.x, pt.y - 24,
00331     _settings_client.gui.population_in_label ? STR_TOWN_LABEL_POP : STR_TOWN_LABEL);
00332   MarkTownSignDirty(t);
00333 }
00334 
00336 void UpdateAllTownVirtCoords()
00337 {
00338   Town *t;
00339   FOR_ALL_TOWNS(t) {
00340     UpdateTownVirtCoord(t);
00341   }
00342 }
00343 
00349 static void ChangePopulation(Town *t, int mod)
00350 {
00351   t->population += mod;
00352   InvalidateWindow(WC_TOWN_VIEW, t->index);
00353   UpdateTownVirtCoord(t);
00354 
00355   InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
00356 }
00357 
00363 uint32 GetWorldPopulation()
00364 {
00365   uint32 pop = 0;
00366   const Town *t;
00367 
00368   FOR_ALL_TOWNS(t) pop += t->population;
00369   return pop;
00370 }
00371 
00376 static void MakeSingleHouseBigger(TileIndex tile)
00377 {
00378   assert(IsTileType(tile, MP_HOUSE));
00379 
00380   /* means it is completed, get out. */
00381   if (LiftHasDestination(tile)) return;
00382 
00383   /* progress in construction stages */
00384   IncHouseConstructionTick(tile);
00385   if (GetHouseConstructionTick(tile) != 0) return;
00386 
00387   const HouseSpec *hs = GetHouseSpecs(GetHouseType(tile));
00388 
00389   /* Check and/or  */
00390   if (HasBit(hs->callback_mask, CBM_HOUSE_CONSTRUCTION_STATE_CHANGE)) {
00391     uint16 callback_res = GetHouseCallback(CBID_HOUSE_CONSTRUCTION_STATE_CHANGE, 0, 0, GetHouseType(tile), GetTownByTile(tile), tile);
00392     if (callback_res != CALLBACK_FAILED) ChangeHouseAnimationFrame(hs->grffile, tile, callback_res);
00393   }
00394 
00395   if (IsHouseCompleted(tile)) {
00396     /* Now that construction is complete, we can add the population of the
00397      * building to the town. */
00398     ChangePopulation(GetTownByTile(tile), hs->population);
00399     ResetHouseAge(tile);
00400   }
00401   MarkTileDirtyByTile(tile);
00402 }
00403 
00407 static void MakeTownHouseBigger(TileIndex tile)
00408 {
00409   uint flags = GetHouseSpecs(GetHouseType(tile))->building_flags;
00410   if (flags & BUILDING_HAS_1_TILE)  MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 0));
00411   if (flags & BUILDING_2_TILES_Y)   MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 1));
00412   if (flags & BUILDING_2_TILES_X)   MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 0));
00413   if (flags & BUILDING_HAS_4_TILES) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 1));
00414 }
00415 
00422 static void TileLoop_Town(TileIndex tile)
00423 {
00424   HouseID house_id = GetHouseType(tile);
00425 
00426   /* NewHouseTileLoop returns false if Callback 21 succeeded, i.e. the house
00427    * doesn't exist any more, so don't continue here. */
00428   if (house_id >= NEW_HOUSE_OFFSET && !NewHouseTileLoop(tile)) return;
00429 
00430   if (!IsHouseCompleted(tile)) {
00431     /* Construction is not completed. See if we can go further in construction*/
00432     MakeTownHouseBigger(tile);
00433     return;
00434   }
00435 
00436   const HouseSpec *hs = GetHouseSpecs(house_id);
00437 
00438   /* If the lift has a destination, it is already an animated tile. */
00439   if ((hs->building_flags & BUILDING_IS_ANIMATED) &&
00440       house_id < NEW_HOUSE_OFFSET &&
00441       !LiftHasDestination(tile) &&
00442       Chance16(1, 2)) {
00443     AddAnimatedTile(tile);
00444   }
00445 
00446   Town *t = GetTownByTile(tile);
00447   uint32 r = Random();
00448 
00449   if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
00450     for (uint i = 0; i < 256; i++) {
00451       uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, r, house_id, t, tile);
00452 
00453       if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
00454 
00455       CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grffile);
00456       if (cargo == CT_INVALID) continue;
00457 
00458       uint amt = GB(callback, 0, 8);
00459       if (amt == 0) continue;
00460 
00461       uint moved = MoveGoodsToStation(tile, 1, 1, cargo, amt);
00462 
00463       const CargoSpec *cs = GetCargo(cargo);
00464       switch (cs->town_effect) {
00465         case TE_PASSENGERS:
00466           t->new_max_pass += amt;
00467           t->new_act_pass += moved;
00468           break;
00469 
00470         case TE_MAIL:
00471           t->new_max_mail += amt;
00472           t->new_act_mail += moved;
00473           break;
00474 
00475         default:
00476           break;
00477       }
00478     }
00479   } else {
00480     if (GB(r, 0, 8) < hs->population) {
00481       uint amt = GB(r, 0, 8) / 8 + 1;
00482 
00483       if (_economy.fluct <= 0) amt = (amt + 1) >> 1;
00484       t->new_max_pass += amt;
00485       t->new_act_pass += MoveGoodsToStation(tile, 1, 1, CT_PASSENGERS, amt);
00486     }
00487 
00488     if (GB(r, 8, 8) < hs->mail_generation) {
00489       uint amt = GB(r, 8, 8) / 8 + 1;
00490 
00491       if (_economy.fluct <= 0) amt = (amt + 1) >> 1;
00492       t->new_max_mail += amt;
00493       t->new_act_mail += MoveGoodsToStation(tile, 1, 1, CT_MAIL, amt);
00494     }
00495   }
00496 
00497   _current_company = OWNER_TOWN;
00498 
00499   if (hs->building_flags & BUILDING_HAS_1_TILE &&
00500       HasBit(t->flags12, TOWN_IS_FUNDED) &&
00501       CanDeleteHouse(tile) &&
00502       GetHouseAge(tile) >= hs->minimum_life &&
00503       --t->time_until_rebuild == 0) {
00504     t->time_until_rebuild = GB(r, 16, 8) + 192;
00505 
00506     ClearTownHouse(t, tile);
00507 
00508     /* Rebuild with another house? */
00509     if (GB(r, 24, 8) >= 12) BuildTownHouse(t, tile);
00510   }
00511 
00512   _current_company = OWNER_NONE;
00513 }
00514 
00515 static CommandCost ClearTile_Town(TileIndex tile, DoCommandFlag flags)
00516 {
00517   if (flags & DC_AUTO) return_cmd_error(STR_2004_BUILDING_MUST_BE_DEMOLISHED);
00518   if (!CanDeleteHouse(tile)) return CMD_ERROR;
00519 
00520   const HouseSpec *hs = GetHouseSpecs(GetHouseType(tile));
00521 
00522   CommandCost cost(EXPENSES_CONSTRUCTION);
00523   cost.AddCost(hs->GetRemovalCost());
00524 
00525   int rating = hs->remove_rating_decrease;
00526   _cleared_town_rating += rating;
00527   Town *t = _cleared_town = GetTownByTile(tile);
00528 
00529   if (IsValidCompanyID(_current_company)) {
00530     if (rating > t->ratings[_current_company] && !(flags & DC_NO_TEST_TOWN_RATING) && !_cheats.magic_bulldozer.value) {
00531       SetDParam(0, t->index);
00532       return_cmd_error(STR_2009_LOCAL_AUTHORITY_REFUSES);
00533     }
00534   }
00535 
00536   ChangeTownRating(t, -rating, RATING_HOUSE_MINIMUM, flags);
00537   if (flags & DC_EXEC) {
00538     ClearTownHouse(t, tile);
00539   }
00540 
00541   return cost;
00542 }
00543 
00544 static void GetProducedCargo_Town(TileIndex tile, CargoID *b)
00545 {
00546   HouseID house_id = GetHouseType(tile);
00547   const HouseSpec *hs = GetHouseSpecs(house_id);
00548   Town *t = GetTownByTile(tile);
00549 
00550   if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
00551     for (uint i = 0; i < 256; i++) {
00552       uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, 0, house_id, t, tile);
00553 
00554       if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
00555 
00556       CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grffile);
00557 
00558       if (cargo == CT_INVALID) continue;
00559       *(b++) = cargo;
00560     }
00561   } else {
00562     if (hs->population > 0) {
00563       *(b++) = CT_PASSENGERS;
00564     }
00565     if (hs->mail_generation > 0) {
00566       *(b++) = CT_MAIL;
00567     }
00568   }
00569 }
00570 
00571 static void GetAcceptedCargo_Town(TileIndex tile, AcceptedCargo ac)
00572 {
00573   const HouseSpec *hs = GetHouseSpecs(GetHouseType(tile));
00574   CargoID accepts[3];
00575 
00576   /* Set the initial accepted cargo types */
00577   for (uint8 i = 0; i < lengthof(accepts); i++) {
00578     accepts[i] = hs->accepts_cargo[i];
00579   }
00580 
00581   /* Check for custom accepted cargo types */
00582   if (HasBit(hs->callback_mask, CBM_HOUSE_ACCEPT_CARGO)) {
00583     uint16 callback = GetHouseCallback(CBID_HOUSE_ACCEPT_CARGO, 0, 0, GetHouseType(tile), GetTownByTile(tile), tile);
00584     if (callback != CALLBACK_FAILED) {
00585       /* Replace accepted cargo types with translated values from callback */
00586       accepts[0] = GetCargoTranslation(GB(callback,  0, 5), hs->grffile);
00587       accepts[1] = GetCargoTranslation(GB(callback,  5, 5), hs->grffile);
00588       accepts[2] = GetCargoTranslation(GB(callback, 10, 5), hs->grffile);
00589     }
00590   }
00591 
00592   /* Check for custom cargo acceptance */
00593   if (HasBit(hs->callback_mask, CBM_HOUSE_CARGO_ACCEPTANCE)) {
00594     uint16 callback = GetHouseCallback(CBID_HOUSE_CARGO_ACCEPTANCE, 0, 0, GetHouseType(tile), GetTownByTile(tile), tile);
00595     if (callback != CALLBACK_FAILED) {
00596       if (accepts[0] != CT_INVALID) ac[accepts[0]] = GB(callback, 0, 4);
00597       if (accepts[1] != CT_INVALID) ac[accepts[1]] = GB(callback, 4, 4);
00598       if (_settings_game.game_creation.landscape != LT_TEMPERATE && HasBit(callback, 12)) {
00599         /* The 'S' bit indicates food instead of goods */
00600         ac[CT_FOOD] = GB(callback, 8, 4);
00601       } else {
00602         if (accepts[2] != CT_INVALID) ac[accepts[2]] = GB(callback, 8, 4);
00603       }
00604       return;
00605     }
00606   }
00607 
00608   /* No custom acceptance, so fill in with the default values */
00609   for (uint8 i = 0; i < lengthof(accepts); i++) {
00610     if (accepts[i] != CT_INVALID) ac[accepts[i]] = hs->cargo_acceptance[i];
00611   }
00612 }
00613 
00614 static void GetTileDesc_Town(TileIndex tile, TileDesc *td)
00615 {
00616   const HouseID house = GetHouseType(tile);
00617   const HouseSpec *hs = GetHouseSpecs(house);
00618   bool house_completed = IsHouseCompleted(tile);
00619 
00620   td->str = hs->building_name;
00621 
00622   uint16 callback_res = GetHouseCallback(CBID_HOUSE_CUSTOM_NAME, house_completed ? 1 : 0, 0, house, GetTownByTile(tile), tile);
00623   if (callback_res != CALLBACK_FAILED) {
00624     StringID new_name = GetGRFStringID(hs->grffile->grfid, 0xD000 + callback_res);
00625     if (new_name != STR_NULL && new_name != STR_UNDEFINED) {
00626       td->str = new_name;
00627     }
00628   }
00629 
00630   if (!house_completed) {
00631     SetDParamX(td->dparam, 0, td->str);
00632     td->str = STR_2058_UNDER_CONSTRUCTION;
00633   }
00634 
00635   if (hs->grffile != NULL) {
00636     const GRFConfig *gc = GetGRFConfig(hs->grffile->grfid);
00637     td->grf = gc->name;
00638   }
00639 
00640   td->owner[0] = OWNER_TOWN;
00641 }
00642 
00643 static TrackStatus GetTileTrackStatus_Town(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
00644 {
00645   /* not used */
00646   return 0;
00647 }
00648 
00649 static void ChangeTileOwner_Town(TileIndex tile, Owner old_owner, Owner new_owner)
00650 {
00651   /* not used */
00652 }
00653 
00654 static bool GrowTown(Town *t);
00655 
00656 static void TownTickHandler(Town *t)
00657 {
00658   if (HasBit(t->flags12, TOWN_IS_FUNDED)) {
00659     int i = t->grow_counter - 1;
00660     if (i < 0) {
00661       if (GrowTown(t)) {
00662         i = t->growth_rate;
00663       } else {
00664         i = 0;
00665       }
00666     }
00667     t->grow_counter = i;
00668   }
00669 
00670   UpdateTownRadius(t);
00671 }
00672 
00673 void OnTick_Town()
00674 {
00675   if (_game_mode == GM_EDITOR) return;
00676 
00677   Town *t;
00678   FOR_ALL_TOWNS(t) {
00679     /* Run town tick at regular intervals, but not all at once. */
00680     if ((_tick_counter + t->index) % TOWN_GROWTH_FREQUENCY == 0) {
00681       TownTickHandler(t);
00682     }
00683   }
00684 }
00685 
00694 static RoadBits GetTownRoadBits(TileIndex tile)
00695 {
00696   if (IsRoadDepotTile(tile) || IsStandardRoadStopTile(tile)) return ROAD_NONE;
00697 
00698   return GetAnyRoadBits(tile, ROADTYPE_ROAD, true);
00699 }
00700 
00711 static bool IsNeighborRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
00712 {
00713   if (!IsValidTile(tile)) return false;
00714 
00715   /* Lookup table for the used diff values */
00716   const TileIndexDiff tid_lt[3] = {
00717     TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90RIGHT)),
00718     TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90LEFT)),
00719     TileOffsByDiagDir(ReverseDiagDir(dir)),
00720   };
00721 
00722   dist_multi = (dist_multi + 1) * 4;
00723   for (uint pos = 4; pos < dist_multi; pos++) {
00724     /* Go (pos / 4) tiles to the left or the right */
00725     TileIndexDiff cur = tid_lt[(pos & 1) ? 0 : 1] * (pos / 4);
00726 
00727     /* Use the current tile as origin, or go one tile backwards */
00728     if (pos & 2) cur += tid_lt[2];
00729 
00730     /* Test for roadbit parallel to dir and facing towards the middle axis */
00731     if (IsValidTile(tile + cur) &&
00732       GetTownRoadBits(TILE_ADD(tile, cur)) & DiagDirToRoadBits((pos & 2) ? dir : ReverseDiagDir(dir))) return true;
00733   }
00734   return false;
00735 }
00736 
00745 static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
00746 {
00747   if (DistanceFromEdge(tile) == 0) return false;
00748 
00749   Slope cur_slope, desired_slope;
00750 
00751   for (;;) {
00752     /* Check if there already is a road at this point? */
00753     if (GetTownRoadBits(tile) == ROAD_NONE) {
00754       /* No, try if we are able to build a road piece there.
00755        * If that fails clear the land, and if that fails exit.
00756        * This is to make sure that we can build a road here later. */
00757       if (CmdFailed(DoCommand(tile, ((dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? ROAD_X : ROAD_Y), 0, DC_AUTO, CMD_BUILD_ROAD)) &&
00758           CmdFailed(DoCommand(tile, 0, 0, DC_AUTO, CMD_LANDSCAPE_CLEAR)))
00759         return false;
00760     }
00761 
00762     cur_slope = _settings_game.construction.build_on_slopes ? GetFoundationSlope(tile, NULL) : GetTileSlope(tile, NULL);
00763     if (cur_slope == SLOPE_FLAT) {
00764 no_slope:
00765       /* Tile has no slope */
00766       switch (t->layout) {
00767         default: NOT_REACHED();
00768 
00769         case TL_ORIGINAL: // Disallow the road if any neighboring tile has a road (distance: 1)
00770           return !IsNeighborRoadTile(tile, dir, 1);
00771 
00772         case TL_BETTER_ROADS: // Disallow the road if any neighboring tile has a road (distance: 1 and 2).
00773           return !IsNeighborRoadTile(tile, dir, 2);
00774       }
00775     }
00776 
00777     /* If the tile is not a slope in the right direction, then
00778      * maybe terraform some. */
00779     desired_slope = (dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? SLOPE_NW : SLOPE_NE;
00780     if (desired_slope != cur_slope && ComplementSlope(desired_slope) != cur_slope) {
00781       if (Chance16(1, 8)) {
00782         CommandCost res = CMD_ERROR;
00783         if (!_generating_world && Chance16(1, 10)) {
00784           /* Note: Do not replace "^ SLOPE_ELEVATED" with ComplementSlope(). The slope might be steep. */
00785           res = DoCommand(tile, Chance16(1, 16) ? cur_slope : cur_slope ^ SLOPE_ELEVATED, 0,
00786               DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
00787         }
00788         if (CmdFailed(res) && Chance16(1, 3)) {
00789           /* We can consider building on the slope, though. */
00790           goto no_slope;
00791         }
00792       }
00793       return false;
00794     }
00795     return true;
00796   }
00797 }
00798 
00799 static bool TerraformTownTile(TileIndex tile, int edges, int dir)
00800 {
00801   assert(tile < MapSize());
00802 
00803   CommandCost r = DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
00804   if (CmdFailed(r) || r.GetCost() >= (_price.terraform + 2) * 8) return false;
00805   DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER | DC_EXEC, CMD_TERRAFORM_LAND);
00806   return true;
00807 }
00808 
00809 static void LevelTownLand(TileIndex tile)
00810 {
00811   assert(tile < MapSize());
00812 
00813   /* Don't terraform if land is plain or if there's a house there. */
00814   if (IsTileType(tile, MP_HOUSE)) return;
00815   Slope tileh = GetTileSlope(tile, NULL);
00816   if (tileh == SLOPE_FLAT) return;
00817 
00818   /* First try up, then down */
00819   if (!TerraformTownTile(tile, ~tileh & SLOPE_ELEVATED, 1)) {
00820     TerraformTownTile(tile, tileh & SLOPE_ELEVATED, 0);
00821   }
00822 }
00823 
00833 static RoadBits GetTownRoadGridElement(Town *t, TileIndex tile, DiagDirection dir)
00834 {
00835   /* align the grid to the downtown */
00836   TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile); // Vector from downtown to the tile
00837   RoadBits rcmd = ROAD_NONE;
00838 
00839   switch (t->layout) {
00840     default: NOT_REACHED();
00841 
00842     case TL_2X2_GRID:
00843       if ((grid_pos.x % 3) == 0) rcmd |= ROAD_Y;
00844       if ((grid_pos.y % 3) == 0) rcmd |= ROAD_X;
00845       break;
00846 
00847     case TL_3X3_GRID:
00848       if ((grid_pos.x % 4) == 0) rcmd |= ROAD_Y;
00849       if ((grid_pos.y % 4) == 0) rcmd |= ROAD_X;
00850       break;
00851   }
00852 
00853   /* Optimise only X-junctions */
00854   if (rcmd != ROAD_ALL) return rcmd;
00855 
00856   RoadBits rb_template;
00857 
00858   switch (GetTileSlope(tile, NULL)) {
00859     default:       rb_template = ROAD_ALL; break;
00860     case SLOPE_W:  rb_template = ROAD_NW | ROAD_SW; break;
00861     case SLOPE_SW: rb_template = ROAD_Y  | ROAD_SW; break;
00862     case SLOPE_S:  rb_template = ROAD_SW | ROAD_SE; break;
00863     case SLOPE_SE: rb_template = ROAD_X  | ROAD_SE; break;
00864     case SLOPE_E:  rb_template = ROAD_SE | ROAD_NE; break;
00865     case SLOPE_NE: rb_template = ROAD_Y  | ROAD_NE; break;
00866     case SLOPE_N:  rb_template = ROAD_NE | ROAD_NW; break;
00867     case SLOPE_NW: rb_template = ROAD_X  | ROAD_NW; break;
00868     case SLOPE_STEEP_W:
00869     case SLOPE_STEEP_S:
00870     case SLOPE_STEEP_E:
00871     case SLOPE_STEEP_N:
00872       rb_template = ROAD_NONE;
00873       break;
00874   }
00875 
00876   /* Stop if the template is compatible to the growth dir */
00877   if (DiagDirToRoadBits(ReverseDiagDir(dir)) & rb_template) return rb_template;
00878   /* If not generate a straight road in the direction of the growth */
00879   return DiagDirToRoadBits(dir) | DiagDirToRoadBits(ReverseDiagDir(dir));
00880 }
00881 
00892 static bool GrowTownWithExtraHouse(Town *t, TileIndex tile)
00893 {
00894   /* We can't look further than that. */
00895   if (DistanceFromEdge(tile) == 0) return false;
00896 
00897   uint counter = 0; // counts the house neighbor tiles
00898 
00899   /* Check the tiles E,N,W and S of the current tile for houses */
00900   for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
00901     /* Count both void and house tiles for checking whether there
00902      * are enough houses in the area. This to make it likely that
00903      * houses get build up to the edge of the map. */
00904     switch (GetTileType(TileAddByDiagDir(tile, dir))) {
00905       case MP_HOUSE:
00906       case MP_VOID:
00907         counter++;
00908         break;
00909 
00910       default:
00911         break;
00912     }
00913 
00914     /* If there are enough neighbors stop here */
00915     if (counter >= 3) {
00916       if (BuildTownHouse(t, tile)) {
00917         _grow_town_result = GROWTH_SUCCEED;
00918         return true;
00919       }
00920       return false;
00921     }
00922   }
00923   return false;
00924 }
00925 
00934 static bool GrowTownWithRoad(const Town *t, TileIndex tile, RoadBits rcmd)
00935 {
00936   if (CmdSucceeded(DoCommand(tile, rcmd, t->index, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD))) {
00937     _grow_town_result = GROWTH_SUCCEED;
00938     return true;
00939   }
00940   return false;
00941 }
00942 
00953 static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
00954 {
00955   assert(bridge_dir < DIAGDIR_END);
00956 
00957   const Slope slope = GetTileSlope(tile, NULL);
00958   if (slope == SLOPE_FLAT) return false; // no slope, no bridge
00959 
00960   /* Make sure the direction is compatible with the slope.
00961    * Well we check if the slope has an up bit set in the
00962    * reverse direction. */
00963   if (HASBITS(slope, InclinedSlope(bridge_dir))) return false;
00964 
00965   /* Assure that the bridge is connectable to the start side */
00966   if (!(GetTownRoadBits(TileAddByDiagDir(tile, ReverseDiagDir(bridge_dir))) & DiagDirToRoadBits(bridge_dir))) return false;
00967 
00968   /* We are in the right direction */
00969   uint8 bridge_length = 0;      // This value stores the length of the possible bridge
00970   TileIndex bridge_tile = tile; // Used to store the other waterside
00971 
00972   const int delta = TileOffsByDiagDir(bridge_dir);
00973   do {
00974     if (bridge_length++ >= 11) {
00975       /* Max 11 tile long bridges */
00976       return false;
00977     }
00978     bridge_tile += delta;
00979   } while (TileX(bridge_tile) != 0 && TileY(bridge_tile) != 0 && IsWaterTile(bridge_tile));
00980 
00981   /* no water tiles in between? */
00982   if (bridge_length == 1) return false;
00983 
00984   for (uint8 times = 0; times <= 22; times++) {
00985     byte bridge_type = RandomRange(MAX_BRIDGES - 1);
00986 
00987     /* Can we actually build the bridge? */
00988     if (CmdSucceeded(DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, DC_AUTO, CMD_BUILD_BRIDGE))) {
00989       DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, DC_EXEC | DC_AUTO, CMD_BUILD_BRIDGE);
00990       _grow_town_result = GROWTH_SUCCEED;
00991       return true;
00992     }
00993   }
00994   /* Quit if it selecting an appropiate bridge type fails a large number of times. */
00995   return false;
00996 }
00997 
01015 static void GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1)
01016 {
01017   RoadBits rcmd = ROAD_NONE;  // RoadBits for the road construction command
01018   TileIndex tile = *tile_ptr; // The main tile on which we base our growth
01019 
01020   assert(tile < MapSize());
01021 
01022   if (cur_rb == ROAD_NONE) {
01023     /* Tile has no road. First reset the status counter
01024      * to say that this is the last iteration. */
01025     _grow_town_result = GROWTH_SEARCH_STOPPED;
01026 
01027     if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
01028 
01029     /* Remove hills etc */
01030     if (!_settings_game.construction.build_on_slopes || Chance16(1, 6)) LevelTownLand(tile);
01031 
01032     /* Is a road allowed here? */
01033     switch (t1->layout) {
01034       default: NOT_REACHED();
01035 
01036       case TL_3X3_GRID:
01037       case TL_2X2_GRID:
01038         rcmd = GetTownRoadGridElement(t1, tile, target_dir);
01039         if (rcmd == ROAD_NONE) return;
01040         break;
01041 
01042       case TL_BETTER_ROADS:
01043       case TL_ORIGINAL:
01044         if (!IsRoadAllowedHere(t1, tile, target_dir)) return;
01045 
01046         DiagDirection source_dir = ReverseDiagDir(target_dir);
01047 
01048         if (Chance16(1, 4)) {
01049           /* Randomize a new target dir */
01050           do target_dir = RandomDiagDir(); while (target_dir == source_dir);
01051         }
01052 
01053         if (!IsRoadAllowedHere(t1, TileAddByDiagDir(tile, target_dir), target_dir)) {
01054           /* A road is not allowed to continue the randomized road,
01055            *  return if the road we're trying to build is curved. */
01056           if (target_dir != ReverseDiagDir(source_dir)) return;
01057 
01058           /* Return if neither side of the new road is a house */
01059           if (!IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90RIGHT)), MP_HOUSE) &&
01060               !IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90LEFT)), MP_HOUSE)) {
01061             return;
01062           }
01063 
01064           /* That means that the road is only allowed if there is a house
01065            *  at any side of the new road. */
01066         }
01067 
01068         rcmd = DiagDirToRoadBits(target_dir) | DiagDirToRoadBits(source_dir);
01069         break;
01070     }
01071 
01072   } else if (target_dir < DIAGDIR_END && !(cur_rb & DiagDirToRoadBits(ReverseDiagDir(target_dir)))) {
01073     /* Continue building on a partial road.
01074      * Should be allways OK, so we only generate
01075      * the fitting RoadBits */
01076     _grow_town_result = GROWTH_SEARCH_STOPPED;
01077 
01078     if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
01079 
01080     switch (t1->layout) {
01081       default: NOT_REACHED();
01082 
01083       case TL_3X3_GRID:
01084       case TL_2X2_GRID:
01085         rcmd = GetTownRoadGridElement(t1, tile, target_dir);
01086         break;
01087 
01088       case TL_BETTER_ROADS:
01089       case TL_ORIGINAL:
01090         rcmd = DiagDirToRoadBits(ReverseDiagDir(target_dir));
01091         break;
01092     }
01093   } else {
01094     bool allow_house = true; // Value which decides if we want to construct a house
01095 
01096     /* Reached a tunnel/bridge? Then continue at the other side of it. */
01097     if (IsTileType(tile, MP_TUNNELBRIDGE)) {
01098       if (GetTunnelBridgeTransportType(tile) == TRANSPORT_ROAD) {
01099         *tile_ptr = GetOtherTunnelBridgeEnd(tile);
01100       }
01101       return;
01102     }
01103 
01104     /* Possibly extend the road in a direction.
01105      * Randomize a direction and if it has a road, bail out. */
01106     target_dir = RandomDiagDir();
01107     if (cur_rb & DiagDirToRoadBits(target_dir)) return;
01108 
01109     /* This is the tile we will reach if we extend to this direction. */
01110     TileIndex house_tile = TileAddByDiagDir(tile, target_dir); // position of a possible house
01111 
01112     /* Don't walk into water. */
01113     if (IsWaterTile(house_tile)) return;
01114 
01115     if (!IsValidTile(house_tile)) return;
01116 
01117     if (_settings_game.economy.allow_town_roads || _generating_world) {
01118       switch (t1->layout) {
01119         default: NOT_REACHED();
01120 
01121         case TL_3X3_GRID: // Use 2x2 grid afterwards!
01122           GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
01123           /* FALL THROUGH */
01124 
01125         case TL_2X2_GRID:
01126           rcmd = GetTownRoadGridElement(t1, house_tile, target_dir);
01127           allow_house = (rcmd == ROAD_NONE);
01128           break;
01129 
01130         case TL_BETTER_ROADS: // Use original afterwards!
01131           GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
01132           /* FALL THROUGH */
01133 
01134         case TL_ORIGINAL:
01135           /* Allow a house at the edge. 60% chance or
01136            * always ok if no road allowed. */
01137           rcmd = DiagDirToRoadBits(target_dir);
01138           allow_house = (!IsRoadAllowedHere(t1, house_tile, target_dir) || Chance16(6, 10));
01139           break;
01140       }
01141     }
01142 
01143     if (allow_house) {
01144       /* Build a house, but not if there already is a house there. */
01145       if (!IsTileType(house_tile, MP_HOUSE)) {
01146         /* Level the land if possible */
01147         if (Chance16(1, 6)) LevelTownLand(house_tile);
01148 
01149         /* And build a house.
01150          * Set result to -1 if we managed to build it. */
01151         if (BuildTownHouse(t1, house_tile)) {
01152           _grow_town_result = GROWTH_SUCCEED;
01153         }
01154       }
01155       return;
01156     }
01157 
01158     _grow_town_result = GROWTH_SEARCH_STOPPED;
01159   }
01160 
01161   /* Return if a water tile */
01162   if (IsWaterTile(tile)) return;
01163 
01164   /* Make the roads look nicer */
01165   rcmd = CleanUpRoadBits(tile, rcmd);
01166   if (rcmd == ROAD_NONE) return;
01167 
01168   /* Only use the target direction for bridges to ensure they're connected.
01169    * The target_dir is as computed previously according to town layout, so
01170    * it will match it perfectly. */
01171   if (GrowTownWithBridge(t1, tile, target_dir)) return;
01172 
01173   GrowTownWithRoad(t1, tile, rcmd);
01174 }
01175 
01181 static int GrowTownAtRoad(Town *t, TileIndex tile)
01182 {
01183   /* Special case.
01184    * @see GrowTownInTile Check the else if
01185    */
01186   DiagDirection target_dir = DIAGDIR_END; // The direction in which we want to extend the town
01187 
01188   assert(tile < MapSize());
01189 
01190   /* Number of times to search.
01191    * Better roads, 2X2 and 3X3 grid grow quite fast so we give
01192    * them a little handicap. */
01193   switch (t->layout) {
01194     case TL_BETTER_ROADS:
01195       _grow_town_result = 10 + t->num_houses * 2 / 9;
01196       break;
01197 
01198     case TL_3X3_GRID:
01199     case TL_2X2_GRID:
01200       _grow_town_result = 10 + t->num_houses * 1 / 9;
01201       break;
01202 
01203     default:
01204       _grow_town_result = 10 + t->num_houses * 4 / 9;
01205       break;
01206   }
01207 
01208   do {
01209     RoadBits cur_rb = GetTownRoadBits(tile); // The RoadBits of the current tile
01210 
01211     /* Try to grow the town from this point */
01212     GrowTownInTile(&tile, cur_rb, target_dir, t);
01213 
01214     /* Exclude the source position from the bitmask
01215      * and return if no more road blocks available */
01216     cur_rb &= ~DiagDirToRoadBits(ReverseDiagDir(target_dir));
01217     if (cur_rb == ROAD_NONE)
01218       return _grow_town_result;
01219 
01220     /* Select a random bit from the blockmask, walk a step
01221      * and continue the search from there. */
01222     do target_dir = RandomDiagDir(); while (!(cur_rb & DiagDirToRoadBits(target_dir)));
01223     tile = TileAddByDiagDir(tile, target_dir);
01224 
01225     if (IsTileType(tile, MP_ROAD) && !IsRoadDepot(tile) && HasTileRoadType(tile, ROADTYPE_ROAD)) {
01226       /* Don't allow building over roads of other cities */
01227       if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN) && GetTownByTile(tile) != t) {
01228         _grow_town_result = GROWTH_SUCCEED;
01229       } else if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_NONE) && _game_mode == GM_EDITOR) {
01230         /* If we are in the SE, and this road-piece has no town owner yet, it just found an
01231          * owner :) (happy happy happy road now) */
01232         SetRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN);
01233         SetTownIndex(tile, t->index);
01234       }
01235     }
01236 
01237     /* Max number of times is checked. */
01238   } while (--_grow_town_result >= 0);
01239 
01240   return (_grow_town_result == -2);
01241 }
01242 
01250 static RoadBits GenRandomRoadBits()
01251 {
01252   uint32 r = Random();
01253   uint a = GB(r, 0, 2);
01254   uint b = GB(r, 8, 2);
01255   if (a == b) b ^= 2;
01256   return (RoadBits)((ROAD_NW << a) + (ROAD_NW << b));
01257 }
01258 
01263 static bool GrowTown(Town *t)
01264 {
01265   static const TileIndexDiffC _town_coord_mod[] = {
01266     {-1,  0},
01267     { 1,  1},
01268     { 1, -1},
01269     {-1, -1},
01270     {-1,  0},
01271     { 0,  2},
01272     { 2,  0},
01273     { 0, -2},
01274     {-1, -1},
01275     {-2,  2},
01276     { 2,  2},
01277     { 2, -2},
01278     { 0,  0}
01279   };
01280 
01281   /* Current "company" is a town */
01282   CompanyID old_company = _current_company;
01283   _current_company = OWNER_TOWN;
01284 
01285   TileIndex tile = t->xy; // The tile we are working with ATM
01286 
01287   /* Find a road that we can base the construction on. */
01288   const TileIndexDiffC *ptr;
01289   for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
01290     if (GetTownRoadBits(tile) != ROAD_NONE) {
01291       int r = GrowTownAtRoad(t, tile);
01292       _current_company = old_company;
01293       return r != 0;
01294     }
01295     tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
01296   }
01297 
01298   /* No road available, try to build a random road block by
01299    * clearing some land and then building a road there. */
01300   if (_settings_game.economy.allow_town_roads || _generating_world) {
01301     tile = t->xy;
01302     for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
01303       /* Only work with plain land that not already has a house */
01304       if (!IsTileType(tile, MP_HOUSE) && GetTileSlope(tile, NULL) == SLOPE_FLAT) {
01305         if (CmdSucceeded(DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR))) {
01306           DoCommand(tile, GenRandomRoadBits(), t->index, DC_EXEC | DC_AUTO, CMD_BUILD_ROAD);
01307           _current_company = old_company;
01308           return true;
01309         }
01310       }
01311       tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
01312     }
01313   }
01314 
01315   _current_company = old_company;
01316   return false;
01317 }
01318 
01319 void UpdateTownRadius(Town *t)
01320 {
01321   static const uint32 _town_squared_town_zone_radius_data[23][5] = {
01322     {  4,  0,  0,  0,  0}, // 0
01323     { 16,  0,  0,  0,  0},
01324     { 25,  0,  0,  0,  0},
01325     { 36,  0,  0,  0,  0},
01326     { 49,  0,  4,  0,  0},
01327     { 64,  0,  4,  0,  0}, // 20
01328     { 64,  0,  9,  0,  1},
01329     { 64,  0,  9,  0,  4},
01330     { 64,  0, 16,  0,  4},
01331     { 81,  0, 16,  0,  4},
01332     { 81,  0, 16,  0,  4}, // 40
01333     { 81,  0, 25,  0,  9},
01334     { 81, 36, 25,  0,  9},
01335     { 81, 36, 25, 16,  9},
01336     { 81, 49,  0, 25,  9},
01337     { 81, 64,  0, 25,  9}, // 60
01338     { 81, 64,  0, 36,  9},
01339     { 81, 64,  0, 36, 16},
01340     {100, 81,  0, 49, 16},
01341     {100, 81,  0, 49, 25},
01342     {121, 81,  0, 49, 25}, // 80
01343     {121, 81,  0, 49, 25},
01344     {121, 81,  0, 49, 36}, // 88
01345   };
01346 
01347   if (t->num_houses < 92) {
01348     memcpy(t->squared_town_zone_radius, _town_squared_town_zone_radius_data[t->num_houses / 4], sizeof(t->squared_town_zone_radius));
01349   } else {
01350     int mass = t->num_houses / 8;
01351     /* Actually we are proportional to sqrt() but that's right because we are covering an area.
01352      * The offsets are to make sure the radii do not decrease in size when going from the table
01353      * to the calculated value.*/
01354     t->squared_town_zone_radius[0] = mass * 15 - 40;
01355     t->squared_town_zone_radius[1] = mass * 9 - 15;
01356     t->squared_town_zone_radius[2] = 0;
01357     t->squared_town_zone_radius[3] = mass * 5 - 5;
01358     t->squared_town_zone_radius[4] = mass * 3 + 5;
01359   }
01360 }
01361 
01362 extern int _nb_orig_names;
01363 
01368 struct TownNameParams {
01369   uint32 grfid;        
01370   uint16 townnametype; 
01371   bool grf;            
01372 
01373   TownNameParams(byte town_name)
01374   {
01375     this->grf = town_name >= _nb_orig_names;
01376     this->grfid = this->grf ? GetGRFTownNameId(town_name - _nb_orig_names) : 0;
01377     this->townnametype = this->grf ? GetGRFTownNameType(town_name - _nb_orig_names) : SPECSTR_TOWNNAME_START + town_name;
01378   }
01379 };
01380 
01387 static bool VerifyTownName(uint32 r, const TownNameParams *par)
01388 {
01389   /* Reserve space for extra unicode character. We need to do this to be able
01390    * to detect too long town name. */
01391   char buf1[MAX_LENGTH_TOWN_NAME_BYTES + MAX_CHAR_LENGTH];
01392   char buf2[MAX_LENGTH_TOWN_NAME_BYTES + MAX_CHAR_LENGTH];
01393 
01394   SetDParam(0, r);
01395   if (par->grf && par->grfid != 0) {
01396     GRFTownNameGenerate(buf1, par->grfid, par->townnametype, r, lastof(buf1));
01397   } else {
01398     GetString(buf1, par->townnametype, lastof(buf1));
01399   }
01400 
01401   /* Check size and width */
01402   if (strlen(buf1) >= MAX_LENGTH_TOWN_NAME_BYTES) return false;
01403 
01404   const Town *t;
01405   FOR_ALL_TOWNS(t) {
01406     /* We can't just compare the numbers since
01407      * several numbers may map to a single name. */
01408     SetDParam(0, t->index);
01409     GetString(buf2, STR_TOWN, lastof(buf2));
01410     if (strcmp(buf1, buf2) == 0) return false;
01411   }
01412 
01413   return true;
01414 }
01415 
01421 bool GenerateTownName(uint32 *townnameparts)
01422 {
01423   /* Do not set too low tries, since when we run out of names, we loop
01424    * for #tries only one time anyway - then we stop generating more
01425    * towns. Do not show it too high neither, since looping through all
01426    * the other towns may take considerable amount of time (10000 is
01427    * too much). */
01428   int tries = 1000;
01429   TownNameParams par(_settings_game.game_creation.town_name);
01430 
01431   assert(townnameparts != NULL);
01432 
01433   for (;;) {
01434     uint32 r = InteractiveRandom();
01435 
01436     if (!VerifyTownName(r, &par)) {
01437       if (tries-- < 0) return false;
01438       continue;
01439     }
01440 
01441     *townnameparts = r;
01442     return true;
01443   }
01444 }
01445 
01446 void UpdateTownMaxPass(Town *t)
01447 {
01448   t->max_pass = t->population >> 3;
01449   t->max_mail = t->population >> 4;
01450 }
01451 
01461 static void DoCreateTown(Town *t, TileIndex tile, uint32 townnameparts, TownSize size, bool city, TownLayout layout)
01462 {
01463   t->xy = tile;
01464   t->num_houses = 0;
01465   t->time_until_rebuild = 10;
01466   UpdateTownRadius(t);
01467   t->flags12 = 0;
01468   t->population = 0;
01469   t->grow_counter = 0;
01470   t->growth_rate = 250;
01471   t->new_max_pass = 0;
01472   t->new_max_mail = 0;
01473   t->new_act_pass = 0;
01474   t->new_act_mail = 0;
01475   t->max_pass = 0;
01476   t->max_mail = 0;
01477   t->act_pass = 0;
01478   t->act_mail = 0;
01479 
01480   t->pct_pass_transported = 0;
01481   t->pct_mail_transported = 0;
01482   t->fund_buildings_months = 0;
01483   t->new_act_food = 0;
01484   t->new_act_water = 0;
01485   t->act_food = 0;
01486   t->act_water = 0;
01487 
01488   for (uint i = 0; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
01489 
01490   t->have_ratings = 0;
01491   t->exclusivity = INVALID_COMPANY;
01492   t->exclusive_counter = 0;
01493   t->statues = 0;
01494 
01495   if (_settings_game.game_creation.town_name < _nb_orig_names) {
01496     /* Original town name */
01497     t->townnamegrfid = 0;
01498     t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
01499   } else {
01500     /* Newgrf town name */
01501     t->townnamegrfid = GetGRFTownNameId(_settings_game.game_creation.town_name  - _nb_orig_names);
01502     t->townnametype  = GetGRFTownNameType(_settings_game.game_creation.town_name - _nb_orig_names);
01503   }
01504   t->townnameparts = townnameparts;
01505 
01506   UpdateTownVirtCoord(t);
01507   InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
01508 
01509   t->InitializeLayout(layout);
01510 
01511   t->larger_town = city;
01512 
01513   int x = (int)size * 16 + 3;
01514   if (size == TS_RANDOM) x = (Random() & 0xF) + 8;
01515   if (city) x *= _settings_game.economy.initial_city_size;
01516 
01517   t->num_houses += x;
01518   UpdateTownRadius(t);
01519 
01520   int i = x * 4;
01521   do {
01522     GrowTown(t);
01523   } while (--i);
01524 
01525   t->num_houses -= x;
01526   UpdateTownRadius(t);
01527   UpdateTownMaxPass(t);
01528   UpdateAirportsNoise();
01529 }
01530 
01541 CommandCost CmdBuildTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01542 {
01543   /* Only in the scenario editor */
01544   if (_game_mode != GM_EDITOR) return CMD_ERROR;
01545 
01546   TownSize size = (TownSize)GB(p1, 0, 2);
01547   bool city = HasBit(p1, 2);
01548   TownLayout layout = (TownLayout)GB(p1, 3, 3);
01549   TownNameParams par(_settings_game.game_creation.town_name);
01550   uint32 townnameparts = p2;
01551 
01552   if (size > TS_RANDOM) return CMD_ERROR;
01553   if (layout > TL_RANDOM) return CMD_ERROR;
01554   if (!VerifyTownName(townnameparts, &par)) return_cmd_error(STR_NAME_MUST_BE_UNIQUE);
01555 
01556   /* Check if too close to the edge of map */
01557   if (DistanceFromEdge(tile) < 12) {
01558     return_cmd_error(STR_0237_TOO_CLOSE_TO_EDGE_OF_MAP);
01559   }
01560 
01561   /* Check distance to all other towns. */
01562   if (IsCloseToTown(tile, 20)) {
01563     return_cmd_error(STR_0238_TOO_CLOSE_TO_ANOTHER_TOWN);
01564   }
01565 
01566   /* Can only build on clear flat areas, possibly with trees. */
01567   if ((!IsTileType(tile, MP_CLEAR) && !IsTileType(tile, MP_TREES)) || GetTileSlope(tile, NULL) != SLOPE_FLAT) {
01568     return_cmd_error(STR_0239_SITE_UNSUITABLE);
01569   }
01570 
01571   /* Allocate town struct */
01572   if (!Town::CanAllocateItem()) return_cmd_error(STR_023A_TOO_MANY_TOWNS);
01573 
01574   /* Create the town */
01575   if (flags & DC_EXEC) {
01576     Town *t = new Town(tile);
01577     _generating_world = true;
01578     UpdateNearestTownForRoadTiles(true);
01579     DoCreateTown(t, tile, townnameparts, size, city, layout);
01580     UpdateNearestTownForRoadTiles(false);
01581     _generating_world = false;
01582   }
01583   return CommandCost();
01584 }
01585 
01586 Town *CreateRandomTown(uint attempts, TownSize size, bool city, TownLayout layout)
01587 {
01588   if (!Town::CanAllocateItem()) return NULL;
01589 
01590   do {
01591     /* Generate a tile index not too close from the edge */
01592     TileIndex tile = RandomTile();
01593     switch (layout) {
01594       case TL_2X2_GRID:
01595         tile = TileXY(TileX(tile) - TileX(tile) % 3, TileY(tile) - TileY(tile) % 3);
01596         break;
01597       case TL_3X3_GRID:
01598         tile = TileXY(TileX(tile) & ~3, TileY(tile) & ~3);
01599         break;
01600       default: break;
01601     }
01602     if (DistanceFromEdge(tile) < 20) continue;
01603 
01604     /* Make sure the tile is plain */
01605     if (!IsTileType(tile, MP_CLEAR) || GetTileSlope(tile, NULL) != SLOPE_FLAT) continue;
01606 
01607     /* Check not too close to a town */
01608     if (IsCloseToTown(tile, 20)) continue;
01609 
01610     uint32 townnameparts;
01611 
01612     /* Get a unique name for the town. */
01613     if (!GenerateTownName(&townnameparts)) break;
01614 
01615     /* Allocate a town struct */
01616     Town *t = new Town(tile);
01617 
01618     DoCreateTown(t, tile, townnameparts, size, city, layout);
01619     return t;
01620   } while (--attempts != 0);
01621 
01622   return NULL;
01623 }
01624 
01625 static const byte _num_initial_towns[4] = {5, 11, 23, 46};  // very low, low, normal, high
01626 
01633 bool GenerateTowns(TownLayout layout)
01634 {
01635   uint num = 0;
01636   uint difficulty = _settings_game.difficulty.number_towns;
01637   uint n = (difficulty == (uint)CUSTOM_TOWN_NUMBER_DIFFICULTY) ? _settings_game.game_creation.custom_town_number : ScaleByMapSize(_num_initial_towns[difficulty] + (Random() & 7));
01638 
01639   SetGeneratingWorldProgress(GWP_TOWN, n);
01640 
01641   /* First attempt will be made at creating the suggested number of towns.
01642    * Note that this is really a suggested value, not a required one.
01643    * We would not like the system to lock up just because the user wanted 100 cities on a 64*64 map, would we? */
01644   do {
01645     bool city = (_settings_game.economy.larger_towns != 0 && Chance16(1, _settings_game.economy.larger_towns));
01646     IncreaseGeneratingWorldProgress(GWP_TOWN);
01647     /* try 20 times to create a random-sized town for the first loop. */
01648     if (CreateRandomTown(20, TS_RANDOM, city, layout) != NULL) num++; // if creation successfull, raise a flag
01649   } while (--n);
01650 
01651   /* If num is still zero at this point, it means that not a single town has been created.
01652    * So give it a last try, but now more aggressive */
01653   if (num == 0 && CreateRandomTown(10000, TS_RANDOM, _settings_game.economy.larger_towns != 0, layout) == NULL) {
01654     if (GetNumTowns() == 0) {
01655       if (_game_mode != GM_EDITOR) {
01656         extern StringID _switch_mode_errorstr;
01657         _switch_mode_errorstr = STR_COULD_NOT_CREATE_TOWN;
01658       }
01659     }
01660     return false;  // we are still without a town? we failed, simply
01661   }
01662   return true;
01663 }
01664 
01665 
01671 HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
01672 {
01673   uint dist = DistanceSquare(tile, t->xy);
01674 
01675   if (t->fund_buildings_months && dist <= 25) return HZB_TOWN_CENTRE;
01676 
01677   HouseZonesBits smallest = HZB_TOWN_EDGE;
01678   for (HouseZonesBits i = HZB_BEGIN; i < HZB_END; i++) {
01679     if (dist < t->squared_town_zone_radius[i]) smallest = i;
01680   }
01681 
01682   return smallest;
01683 }
01684 
01695 static inline void ClearMakeHouseTile(TileIndex tile, Town *t, byte counter, byte stage, HouseID type, byte random_bits)
01696 {
01697   CommandCost cc = DoCommand(tile, 0, 0, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR);
01698 
01699   assert(CmdSucceeded(cc));
01700 
01701   IncreaseBuildingCount(t, type);
01702   MakeHouseTile(tile, t->index, counter, stage, type, random_bits);
01703   if (GetHouseSpecs(type)->building_flags & BUILDING_IS_ANIMATED) AddAnimatedTile(tile);
01704 
01705   MarkTileDirtyByTile(tile);
01706 }
01707 
01708 
01719 static void MakeTownHouse(TileIndex t, Town *town, byte counter, byte stage, HouseID type, byte random_bits)
01720 {
01721   BuildingFlags size = GetHouseSpecs(type)->building_flags;
01722 
01723   ClearMakeHouseTile(t, town, counter, stage, type, random_bits);
01724   if (size & BUILDING_2_TILES_Y)   ClearMakeHouseTile(t + TileDiffXY(0, 1), town, counter, stage, ++type, random_bits);
01725   if (size & BUILDING_2_TILES_X)   ClearMakeHouseTile(t + TileDiffXY(1, 0), town, counter, stage, ++type, random_bits);
01726   if (size & BUILDING_HAS_4_TILES) ClearMakeHouseTile(t + TileDiffXY(1, 1), town, counter, stage, ++type, random_bits);
01727 }
01728 
01729 
01738 static inline bool CanBuildHouseHere(TileIndex tile, TownID town, bool noslope)
01739 {
01740   /* cannot build on these slopes... */
01741   Slope slope = GetTileSlope(tile, NULL);
01742   if ((noslope && slope != SLOPE_FLAT) || IsSteepSlope(slope)) return false;
01743 
01744   /* building under a bridge? */
01745   if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return false;
01746 
01747   /* do not try to build over house owned by another town */
01748   if (IsTileType(tile, MP_HOUSE) && GetTownIndex(tile) != town) return false;
01749 
01750   /* can we clear the land? */
01751   return CmdSucceeded(DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR));
01752 }
01753 
01754 
01764 static inline bool CheckBuildHouseSameZ(TileIndex tile, TownID town, uint z, bool noslope)
01765 {
01766   if (!CanBuildHouseHere(tile, town, noslope)) return false;
01767 
01768   /* if building on slopes is allowed, there will be flattening foundation (to tile max z) */
01769   if (GetTileMaxZ(tile) != z) return false;
01770 
01771   return true;
01772 }
01773 
01774 
01784 static bool CheckFree2x2Area(TileIndex tile, TownID town, uint z, bool noslope)
01785 {
01786   /* we need to check this tile too because we can be at different tile now */
01787   if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
01788 
01789   for (DiagDirection d = DIAGDIR_SE; d < DIAGDIR_END; d++) {
01790     tile += TileOffsByDiagDir(d);
01791     if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
01792   }
01793 
01794   return true;
01795 }
01796 
01797 
01805 static inline bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile)
01806 {
01807   /* Allow towns everywhere when we don't build roads */
01808   if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
01809 
01810   TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
01811 
01812   switch (t->layout) {
01813     case TL_2X2_GRID:
01814       if ((grid_pos.x % 3) == 0 || (grid_pos.y % 3) == 0) return false;
01815       break;
01816 
01817     case TL_3X3_GRID:
01818       if ((grid_pos.x % 4) == 0 || (grid_pos.y % 4) == 0) return false;
01819       break;
01820 
01821     default:
01822       break;
01823   }
01824 
01825   return true;
01826 }
01827 
01828 
01836 static inline bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile)
01837 {
01838   /* Allow towns everywhere when we don't build roads */
01839   if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
01840 
01841   /* MapSize() is sure dividable by both MapSizeX() and MapSizeY(),
01842    * so to do only one memory access, use MapSize() */
01843   uint dx = MapSize() + TileX(t->xy) - TileX(tile);
01844   uint dy = MapSize() + TileY(t->xy) - TileY(tile);
01845 
01846   switch (t->layout) {
01847     case TL_2X2_GRID:
01848       if ((dx % 3) != 0 || (dy % 3) != 0) return false;
01849       break;
01850 
01851     case TL_3X3_GRID:
01852       if ((dx % 4) < 2 || (dy % 4) < 2) return false;
01853       break;
01854 
01855     default:
01856       break;
01857   }
01858 
01859   return true;
01860 }
01861 
01862 
01872 static bool CheckTownBuild2House(TileIndex *tile, Town *t, uint maxz, bool noslope, DiagDirection second)
01873 {
01874   /* 'tile' is already checked in BuildTownHouse() - CanBuildHouseHere() and slope test */
01875 
01876   TileIndex tile2 = *tile + TileOffsByDiagDir(second);
01877   if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) return true;
01878 
01879   tile2 = *tile + TileOffsByDiagDir(ReverseDiagDir(second));
01880   if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) {
01881     *tile = tile2;
01882     return true;
01883   }
01884 
01885   return false;
01886 }
01887 
01888 
01897 static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, uint maxz, bool noslope)
01898 {
01899   TileIndex tile2 = *tile;
01900 
01901   for (DiagDirection d = DIAGDIR_SE;;d++) { // 'd' goes through DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_END
01902     if (TownLayoutAllows2x2HouseHere(t, tile2) && CheckFree2x2Area(tile2, t->index, maxz, noslope)) {
01903       *tile = tile2;
01904       return true;
01905     }
01906     if (d == DIAGDIR_END) break;
01907     tile2 += TileOffsByDiagDir(ReverseDiagDir(d)); // go clockwise
01908   }
01909 
01910   return false;
01911 }
01912 
01913 
01920 static bool BuildTownHouse(Town *t, TileIndex tile)
01921 {
01922   /* forbidden building here by town layout */
01923   if (!TownLayoutAllowsHouseHere(t, tile)) return false;
01924 
01925   /* no house allowed at all, bail out */
01926   if (!CanBuildHouseHere(tile, t->index, false)) return false;
01927 
01928   uint z;
01929   Slope slope = GetTileSlope(tile, &z);
01930 
01931   /* Get the town zone type of the current tile, as well as the climate.
01932    * This will allow to easily compare with the specs of the new house to build */
01933   HouseZonesBits rad = GetTownRadiusGroup(t, tile);
01934 
01935   /* Above snow? */
01936   int land = _settings_game.game_creation.landscape;
01937   if (land == LT_ARCTIC && z >= _settings_game.game_creation.snow_line) land = -1;
01938 
01939   uint bitmask = (1 << rad) + (1 << (land + 12));
01940 
01941   /* bits 0-4 are used
01942    * bits 11-15 are used
01943    * bits 5-10 are not used. */
01944   HouseID houses[HOUSE_MAX];
01945   uint num = 0;
01946   uint probs[HOUSE_MAX];
01947   uint probability_max = 0;
01948 
01949   /* Generate a list of all possible houses that can be built. */
01950   for (uint i = 0; i < HOUSE_MAX; i++) {
01951     const HouseSpec *hs = GetHouseSpecs(i);
01952 
01953     /* Verify that the candidate house spec matches the current tile status */
01954     if ((~hs->building_availability & bitmask) != 0 || !hs->enabled) continue;
01955 
01956     /* Don't let these counters overflow. Global counters are 32bit, there will never be that many houses. */
01957     if (hs->class_id != HOUSE_NO_CLASS) {
01958       /* id_count is always <= class_count, so it doesn't need to be checked */
01959       if (t->building_counts.class_count[hs->class_id] == UINT16_MAX) continue;
01960     } else {
01961       /* If the house has no class, check id_count instead */
01962       if (t->building_counts.id_count[i] == UINT16_MAX) continue;
01963     }
01964 
01965     /* Without NewHouses, all houses have probability '1' */
01966     uint cur_prob = (_loaded_newgrf_features.has_newhouses ? hs->probability : 1);
01967     probability_max += cur_prob;
01968     probs[num] = cur_prob;
01969     houses[num++] = (HouseID)i;
01970   }
01971 
01972   uint maxz = GetTileMaxZ(tile);
01973 
01974   while (probability_max > 0) {
01975     uint r = RandomRange(probability_max);
01976     uint i;
01977     for (i = 0; i < num; i++) {
01978       if (probs[i] > r) break;
01979       r -= probs[i];
01980     }
01981 
01982     HouseID house = houses[i];
01983     probability_max -= probs[i];
01984 
01985     /* remove tested house from the set */
01986     num--;
01987     houses[i] = houses[num];
01988     probs[i] = probs[num];
01989 
01990     const HouseSpec *hs = GetHouseSpecs(house);
01991 
01992     if (_loaded_newgrf_features.has_newhouses) {
01993       if (hs->override != 0) {
01994         house = hs->override;
01995         hs = GetHouseSpecs(house);
01996       }
01997 
01998       if ((hs->extra_flags & BUILDING_IS_HISTORICAL) && !_generating_world && _game_mode != GM_EDITOR) continue;
01999     }
02000 
02001     if (_cur_year < hs->min_year || _cur_year > hs->max_year) continue;
02002 
02003     /* Special houses that there can be only one of. */
02004     uint oneof = 0;
02005 
02006     if (hs->building_flags & BUILDING_IS_CHURCH) {
02007       SetBit(oneof, TOWN_HAS_CHURCH);
02008     } else if (hs->building_flags & BUILDING_IS_STADIUM) {
02009       SetBit(oneof, TOWN_HAS_STADIUM);
02010     }
02011 
02012     if (HASBITS(t->flags12, oneof)) continue;
02013 
02014     /* Make sure there is no slope? */
02015     bool noslope = (hs->building_flags & TILE_NOT_SLOPED) != 0;
02016     if (noslope && slope != SLOPE_FLAT) continue;
02017 
02018     if (hs->building_flags & TILE_SIZE_2x2) {
02019       if (!CheckTownBuild2x2House(&tile, t, maxz, noslope)) continue;
02020     } else if (hs->building_flags & TILE_SIZE_2x1) {
02021       if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SW)) continue;
02022     } else if (hs->building_flags & TILE_SIZE_1x2) {
02023       if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SE)) continue;
02024     } else {
02025       /* 1x1 house checks are already done */
02026     }
02027 
02028     if (HasBit(hs->callback_mask, CBM_HOUSE_ALLOW_CONSTRUCTION)) {
02029       uint16 callback_res = GetHouseCallback(CBID_HOUSE_ALLOW_CONSTRUCTION, 0, 0, house, t, tile);
02030       if (callback_res != CALLBACK_FAILED && GB(callback_res, 0, 8) == 0) continue;
02031     }
02032 
02033     /* build the house */
02034     t->num_houses++;
02035 
02036     /* Special houses that there can be only one of. */
02037     t->flags12 |= oneof;
02038 
02039     byte construction_counter = 0;
02040     byte construction_stage = 0;
02041 
02042     if (_generating_world || _game_mode == GM_EDITOR) {
02043       uint32 r = Random();
02044 
02045       construction_stage = TOWN_HOUSE_COMPLETED;
02046       if (Chance16(1, 7)) construction_stage = GB(r, 0, 2);
02047 
02048       if (construction_stage == TOWN_HOUSE_COMPLETED) {
02049         ChangePopulation(t, hs->population);
02050       } else {
02051         construction_counter = GB(r, 2, 2);
02052       }
02053     }
02054 
02055     MakeTownHouse(tile, t, construction_counter, construction_stage, house, Random());
02056 
02057     return true;
02058   }
02059 
02060   return false;
02061 }
02062 
02069 static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
02070 {
02071   assert(IsTileType(tile, MP_HOUSE));
02072   DecreaseBuildingCount(t, house);
02073   DoClearSquare(tile);
02074   DeleteAnimatedTile(tile);
02075 }
02076 
02084 TileIndexDiff GetHouseNorthPart(HouseID &house)
02085 {
02086   if (house >= 3) { // house id 0,1,2 MUST be single tile houses, or this code breaks.
02087     if (GetHouseSpecs(house - 1)->building_flags & TILE_SIZE_2x1) {
02088       house--;
02089       return TileDiffXY(-1, 0);
02090     } else if (GetHouseSpecs(house - 1)->building_flags & BUILDING_2_TILES_Y) {
02091       house--;
02092       return TileDiffXY(0, -1);
02093     } else if (GetHouseSpecs(house - 2)->building_flags & BUILDING_HAS_4_TILES) {
02094       house -= 2;
02095       return TileDiffXY(-1, 0);
02096     } else if (GetHouseSpecs(house - 3)->building_flags & BUILDING_HAS_4_TILES) {
02097       house -= 3;
02098       return TileDiffXY(-1, -1);
02099     }
02100   }
02101   return 0;
02102 }
02103 
02104 void ClearTownHouse(Town *t, TileIndex tile)
02105 {
02106   assert(IsTileType(tile, MP_HOUSE));
02107 
02108   HouseID house = GetHouseType(tile);
02109 
02110   /* need to align the tile to point to the upper left corner of the house */
02111   tile += GetHouseNorthPart(house); // modifies house to the ID of the north tile
02112 
02113   const HouseSpec *hs = GetHouseSpecs(house);
02114 
02115   /* Remove population from the town if the house is finished. */
02116   if (IsHouseCompleted(tile)) {
02117     ChangePopulation(t, -hs->population);
02118   }
02119 
02120   t->num_houses--;
02121 
02122   /* Clear flags for houses that only may exist once/town. */
02123   if (hs->building_flags & BUILDING_IS_CHURCH) {
02124     ClrBit(t->flags12, TOWN_HAS_CHURCH);
02125   } else if (hs->building_flags & BUILDING_IS_STADIUM) {
02126     ClrBit(t->flags12, TOWN_HAS_STADIUM);
02127   }
02128 
02129   /* Do the actual clearing of tiles */
02130   uint eflags = hs->building_flags;
02131   DoClearTownHouseHelper(tile, t, house);
02132   if (eflags & BUILDING_2_TILES_Y)   DoClearTownHouseHelper(tile + TileDiffXY(0, 1), t, ++house);
02133   if (eflags & BUILDING_2_TILES_X)   DoClearTownHouseHelper(tile + TileDiffXY(1, 0), t, ++house);
02134   if (eflags & BUILDING_HAS_4_TILES) DoClearTownHouseHelper(tile + TileDiffXY(1, 1), t, ++house);
02135 }
02136 
02137 static bool IsUniqueTownName(const char *name)
02138 {
02139   const Town *t;
02140 
02141   FOR_ALL_TOWNS(t) {
02142     if (t->name != NULL && strcmp(t->name, name) == 0) return false;
02143   }
02144 
02145   return true;
02146 }
02147 
02154 CommandCost CmdRenameTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02155 {
02156   if (!IsValidTownID(p1)) return CMD_ERROR;
02157 
02158   bool reset = StrEmpty(text);
02159 
02160   if (!reset) {
02161     if (strlen(text) >= MAX_LENGTH_TOWN_NAME_BYTES) return CMD_ERROR;
02162     if (!IsUniqueTownName(text)) return_cmd_error(STR_NAME_MUST_BE_UNIQUE);
02163   }
02164 
02165   if (flags & DC_EXEC) {
02166     Town *t = GetTown(p1);
02167 
02168     free(t->name);
02169     t->name = reset ? NULL : strdup(text);
02170 
02171     UpdateTownVirtCoord(t);
02172     InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
02173     UpdateAllStationVirtCoord();
02174     UpdateAllWaypointSigns();
02175     MarkWholeScreenDirty();
02176   }
02177   return CommandCost();
02178 }
02179 
02181 void ExpandTown(Town *t)
02182 {
02183   /* Warn the users if towns are not allowed to build roads,
02184    * but do this only onces per openttd run. */
02185   static bool warned_no_roads = false;
02186   if (!_settings_game.economy.allow_town_roads && !warned_no_roads) {
02187     ShowErrorMessage(INVALID_STRING_ID, STR_TOWN_EXPAND_WARN_NO_ROADS, 0, 0);
02188     warned_no_roads = true;
02189   }
02190 
02191   /* The more houses, the faster we grow */
02192   uint amount = RandomRange(ClampToU16(t->num_houses / 10)) + 3;
02193   t->num_houses += amount;
02194   UpdateTownRadius(t);
02195 
02196   uint n = amount * 10;
02197   do GrowTown(t); while (--n);
02198 
02199   t->num_houses -= amount;
02200   UpdateTownRadius(t);
02201 
02202   UpdateTownMaxPass(t);
02203 }
02204 
02205 extern const byte _town_action_costs[8] = {
02206   2, 4, 9, 35, 48, 53, 117, 175
02207 };
02208 
02209 static void TownActionAdvertiseSmall(Town *t)
02210 {
02211   ModifyStationRatingAround(t->xy, _current_company, 0x40, 10);
02212 }
02213 
02214 static void TownActionAdvertiseMedium(Town *t)
02215 {
02216   ModifyStationRatingAround(t->xy, _current_company, 0x70, 15);
02217 }
02218 
02219 static void TownActionAdvertiseLarge(Town *t)
02220 {
02221   ModifyStationRatingAround(t->xy, _current_company, 0xA0, 20);
02222 }
02223 
02224 static void TownActionRoadRebuild(Town *t)
02225 {
02226   t->road_build_months = 6;
02227 
02228   char company_name[MAX_LENGTH_COMPANY_NAME_BYTES];
02229   SetDParam(0, _current_company);
02230   GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
02231 
02232   char *cn = strdup(company_name);
02233   SetDParam(0, t->index);
02234   SetDParamStr(1, cn);
02235 
02236   AddNewsItem(STR_2055_TRAFFIC_CHAOS_IN_ROAD_REBUILDING, NS_GENERAL, t->xy, 0, cn);
02237 }
02238 
02239 static bool DoBuildStatueOfCompany(TileIndex tile, TownID town_id)
02240 {
02241   /* Statues can be build on slopes, just like houses. Only the steep slopes is a no go. */
02242   if (IsSteepSlope(GetTileSlope(tile, NULL))) return false;
02243   /* Don't build statues under bridges. */
02244   if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return false;
02245 
02246   if (!IsTileType(tile, MP_HOUSE) &&
02247       !IsTileType(tile, MP_CLEAR) &&
02248       !IsTileType(tile, MP_TREES)) {
02249     return false;
02250   }
02251 
02252   CompanyID old = _current_company;
02253   _current_company = OWNER_NONE;
02254   CommandCost r = DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
02255   _current_company = old;
02256 
02257   if (CmdFailed(r)) return false;
02258 
02259   MakeStatue(tile, _current_company, town_id);
02260   MarkTileDirtyByTile(tile);
02261 
02262   return true;
02263 }
02264 
02271 static bool SearchTileForStatue(TileIndex tile, void *user_data)
02272 {
02273   TownID *town_id = (TownID *)user_data;
02274   return DoBuildStatueOfCompany(tile, *town_id);
02275 }
02276 
02282 static void TownActionBuildStatue(Town *t)
02283 {
02284   TileIndex tile = t->xy;
02285 
02286   if (CircularTileSearch(&tile, 9, SearchTileForStatue, &t->index)) {
02287     SetBit(t->statues, _current_company); // Once found and built, "inform" the Town
02288   }
02289 }
02290 
02291 static void TownActionFundBuildings(Town *t)
02292 {
02293   /* Build next tick */
02294   t->grow_counter = 1;
02295   /* If we were not already growing */
02296   SetBit(t->flags12, TOWN_IS_FUNDED);
02297   /* And grow for 3 months */
02298   t->fund_buildings_months = 3;
02299 }
02300 
02301 static void TownActionBuyRights(Town *t)
02302 {
02303   /* Check if it's allowed to by the rights */
02304   if (!_settings_game.economy.exclusive_rights) return;
02305 
02306   t->exclusive_counter = 12;
02307   t->exclusivity = _current_company;
02308 
02309   ModifyStationRatingAround(t->xy, _current_company, 130, 17);
02310 }
02311 
02312 static void TownActionBribe(Town *t)
02313 {
02314   if (Chance16(1, 14)) {
02315     /* set as unwanted for 6 months */
02316     t->unwanted[_current_company] = 6;
02317 
02318     /* set all close by station ratings to 0 */
02319     Station *st;
02320     FOR_ALL_STATIONS(st) {
02321       if (st->town == t && st->owner == _current_company) {
02322         for (CargoID i = 0; i < NUM_CARGO; i++) st->goods[i].rating = 0;
02323       }
02324     }
02325 
02326     /* only show errormessage to the executing player. All errors are handled command.c
02327      * but this is special, because it can only 'fail' on a DC_EXEC */
02328     if (IsLocalCompany()) ShowErrorMessage(STR_BRIBE_FAILED_2, STR_BRIBE_FAILED, 0, 0);
02329 
02330     /* decrease by a lot!
02331      * ChangeTownRating is only for stuff in demolishing. Bribe failure should
02332      * be independent of any cheat settings
02333      */
02334     if (t->ratings[_current_company] > RATING_BRIBE_DOWN_TO) {
02335       t->ratings[_current_company] = RATING_BRIBE_DOWN_TO;
02336       InvalidateWindow(WC_TOWN_AUTHORITY, t->index);
02337     }
02338   } else {
02339     ChangeTownRating(t, RATING_BRIBE_UP_STEP, RATING_BRIBE_MAXIMUM, DC_EXEC);
02340   }
02341 }
02342 
02343 typedef void TownActionProc(Town *t);
02344 static TownActionProc * const _town_action_proc[] = {
02345   TownActionAdvertiseSmall,
02346   TownActionAdvertiseMedium,
02347   TownActionAdvertiseLarge,
02348   TownActionRoadRebuild,
02349   TownActionBuildStatue,
02350   TownActionFundBuildings,
02351   TownActionBuyRights,
02352   TownActionBribe
02353 };
02354 
02355 enum TownActions {
02356   TACT_NONE             = 0x00,
02357 
02358   TACT_ADVERTISE_SMALL  = 0x01,
02359   TACT_ADVERTISE_MEDIUM = 0x02,
02360   TACT_ADVERTISE_LARGE  = 0x04,
02361   TACT_ROAD_REBUILD     = 0x08,
02362   TACT_BUILD_STATUE     = 0x10,
02363   TACT_FOUND_BUILDINGS  = 0x20,
02364   TACT_BUY_RIGHTS       = 0x40,
02365   TACT_BRIBE            = 0x80,
02366 
02367   TACT_ADVERTISE        = TACT_ADVERTISE_SMALL | TACT_ADVERTISE_MEDIUM | TACT_ADVERTISE_LARGE,
02368   TACT_CONSTRUCTION     = TACT_ROAD_REBUILD | TACT_BUILD_STATUE | TACT_FOUND_BUILDINGS,
02369   TACT_FUNDS            = TACT_BUY_RIGHTS | TACT_BRIBE,
02370   TACT_ALL              = TACT_ADVERTISE | TACT_CONSTRUCTION | TACT_FUNDS,
02371 };
02372 
02373 DECLARE_ENUM_AS_BIT_SET(TownActions);
02374 
02381 uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t)
02382 {
02383   int num = 0;
02384   TownActions buttons = TACT_NONE;
02385 
02386   /* Spectators and unwanted have no options */
02387   if (cid != COMPANY_SPECTATOR && !(_settings_game.economy.bribe && t->unwanted[cid])) {
02388 
02389     /* Things worth more than this are not shown */
02390     Money avail = GetCompany(cid)->money + _price.station_value * 200;
02391     Money ref = _price.build_industry >> 8;
02392 
02393     /* Check the action bits for validity and
02394      * if they are valid add them */
02395     for (uint i = 0; i != lengthof(_town_action_costs); i++) {
02396       const TownActions cur = (TownActions)(1 << i);
02397 
02398       /* Is the company not able to bribe ? */
02399       if (cur == TACT_BRIBE && (!_settings_game.economy.bribe || t->ratings[cid] >= RATING_BRIBE_MAXIMUM))
02400         continue;
02401 
02402       /* Is the company not able to buy exclusive rights ? */
02403       if (cur == TACT_BUY_RIGHTS && !_settings_game.economy.exclusive_rights)
02404         continue;
02405 
02406       /* Is the company not able to build a statue ? */
02407       if (cur == TACT_BUILD_STATUE && HasBit(t->statues, cid))
02408         continue;
02409 
02410       if (avail >= _town_action_costs[i] * ref) {
02411         buttons |= cur;
02412         num++;
02413       }
02414     }
02415   }
02416 
02417   if (nump != NULL) *nump = num;
02418   return buttons;
02419 }
02420 
02429 CommandCost CmdDoTownAction(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02430 {
02431   if (!IsValidTownID(p1) || p2 >= lengthof(_town_action_proc)) return CMD_ERROR;
02432 
02433   Town *t = GetTown(p1);
02434 
02435   if (!HasBit(GetMaskOfTownActions(NULL, _current_company, t), p2)) return CMD_ERROR;
02436 
02437   CommandCost cost(EXPENSES_OTHER, (_price.build_industry >> 8) * _town_action_costs[p2]);
02438 
02439   if (flags & DC_EXEC) {
02440     _town_action_proc[p2](t);
02441     InvalidateWindow(WC_TOWN_AUTHORITY, p1);
02442   }
02443 
02444   return cost;
02445 }
02446 
02447 static void UpdateTownGrowRate(Town *t)
02448 {
02449   /* Increase company ratings if they're low */
02450   const Company *c;
02451   FOR_ALL_COMPANIES(c) {
02452     if (t->ratings[c->index] < RATING_GROWTH_MAXIMUM) {
02453       t->ratings[c->index] = min((int)RATING_GROWTH_MAXIMUM, t->ratings[c->index] + RATING_GROWTH_UP_STEP);
02454     }
02455   }
02456 
02457   int n = 0;
02458 
02459   const Station *st;
02460   FOR_ALL_STATIONS(st) {
02461     if (DistanceSquare(st->xy, t->xy) <= t->squared_town_zone_radius[0]) {
02462       if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
02463         n++;
02464         if (IsValidCompanyID(st->owner)) {
02465           int new_rating = t->ratings[st->owner] + RATING_STATION_UP_STEP;
02466           t->ratings[st->owner] = min(new_rating, INT16_MAX); // do not let it overflow
02467         }
02468       } else {
02469         if (IsValidCompanyID(st->owner)) {
02470           int new_rating = t->ratings[st->owner] + RATING_STATION_DOWN_STEP;
02471           t->ratings[st->owner] = max(new_rating, INT16_MIN);
02472         }
02473       }
02474     }
02475   }
02476 
02477   /* clamp all ratings to valid values */
02478   for (uint i = 0; i < MAX_COMPANIES; i++) {
02479     t->ratings[i] = Clamp(t->ratings[i], RATING_MINIMUM, RATING_MAXIMUM);
02480   }
02481 
02482   InvalidateWindow(WC_TOWN_AUTHORITY, t->index);
02483 
02484   ClrBit(t->flags12, TOWN_IS_FUNDED);
02485   if (_settings_game.economy.town_growth_rate == 0 && t->fund_buildings_months == 0) return;
02486 
02489   static const uint16 _grow_count_values[2][6] = {
02490     { 120, 120, 120, 100,  80,  60 }, // Fund new buildings has been activated
02491     { 320, 420, 300, 220, 160, 100 }  // Normal values
02492   };
02493 
02494   uint16 m;
02495 
02496   if (t->fund_buildings_months != 0) {
02497     m = _grow_count_values[0][min(n, 5)];
02498     t->fund_buildings_months--;
02499   } else {
02500     m = _grow_count_values[1][min(n, 5)];
02501     if (n == 0 && !Chance16(1, 12)) return;
02502   }
02503 
02504   if (_settings_game.game_creation.landscape == LT_ARCTIC) {
02505     if (TilePixelHeight(t->xy) >= GetSnowLine() && t->act_food == 0 && t->population > 90)
02506       return;
02507   } else if (_settings_game.game_creation.landscape == LT_TROPIC) {
02508     if (GetTropicZone(t->xy) == TROPICZONE_DESERT && (t->act_food == 0 || t->act_water == 0) && t->population > 60)
02509       return;
02510   }
02511 
02512   /* Use the normal growth rate values if new buildings have been funded in
02513    * this town and the growth rate is set to none. */
02514   uint growth_multiplier = _settings_game.economy.town_growth_rate != 0 ? _settings_game.economy.town_growth_rate - 1 : 1;
02515 
02516   m >>= growth_multiplier;
02517   if (t->larger_town) m /= 2;
02518 
02519   t->growth_rate = m / (t->num_houses / 50 + 1);
02520   if (m <= t->grow_counter)
02521     t->grow_counter = m;
02522 
02523   SetBit(t->flags12, TOWN_IS_FUNDED);
02524 }
02525 
02526 static void UpdateTownAmounts(Town *t)
02527 {
02528   /* Using +1 here to prevent overflow and division by zero */
02529   t->pct_pass_transported = t->new_act_pass * 256 / (t->new_max_pass + 1);
02530 
02531   t->max_pass = t->new_max_pass; t->new_max_pass = 0;
02532   t->act_pass = t->new_act_pass; t->new_act_pass = 0;
02533   t->act_food = t->new_act_food; t->new_act_food = 0;
02534   t->act_water = t->new_act_water; t->new_act_water = 0;
02535 
02536   /* Using +1 here to prevent overflow and division by zero */
02537   t->pct_mail_transported = t->new_act_mail * 256 / (t->new_max_mail + 1);
02538   t->max_mail = t->new_max_mail; t->new_max_mail = 0;
02539   t->act_mail = t->new_act_mail; t->new_act_mail = 0;
02540 
02541   InvalidateWindow(WC_TOWN_VIEW, t->index);
02542 }
02543 
02544 static void UpdateTownUnwanted(Town *t)
02545 {
02546   const Company *c;
02547 
02548   FOR_ALL_COMPANIES(c) {
02549     if (t->unwanted[c->index] > 0) t->unwanted[c->index]--;
02550   }
02551 }
02552 
02558 bool CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags)
02559 {
02560   if (!IsValidCompanyID(_current_company) || (flags & DC_NO_TEST_TOWN_RATING)) return true;
02561 
02562   Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
02563   if (t == NULL) return true;
02564 
02565   if (t->ratings[_current_company] > RATING_VERYPOOR) return true;
02566 
02567   _error_message = STR_2009_LOCAL_AUTHORITY_REFUSES;
02568   SetDParam(0, t->index);
02569 
02570   return false;
02571 }
02572 
02573 
02574 Town *CalcClosestTownFromTile(TileIndex tile, uint threshold)
02575 {
02576   Town *t;
02577   uint best = threshold;
02578   Town *best_town = NULL;
02579 
02580   FOR_ALL_TOWNS(t) {
02581     uint dist = DistanceManhattan(tile, t->xy);
02582     if (dist < best) {
02583       best = dist;
02584       best_town = t;
02585     }
02586   }
02587 
02588   return best_town;
02589 }
02590 
02591 
02592 Town *ClosestTownFromTile(TileIndex tile, uint threshold)
02593 {
02594   switch (GetTileType(tile)) {
02595     case MP_ROAD:
02596       if (!HasTownOwnedRoad(tile)) {
02597         TownID tid = GetTownIndex(tile);
02598         if (tid == (TownID)INVALID_TOWN) {
02599           /* in the case we are generating "many random towns", this value may be INVALID_TOWN */
02600           if (_generating_world) return CalcClosestTownFromTile(tile, threshold);
02601           assert(GetNumTowns() == 0);
02602           return NULL;
02603         }
02604 
02605         Town *town = GetTown(tid);
02606         assert(town->IsValid());
02607 
02608         if (DistanceManhattan(tile, town->xy) >= threshold) town = NULL;
02609 
02610         return town;
02611       }
02612       /* FALL THROUGH */
02613 
02614     case MP_HOUSE:
02615       return GetTownByTile(tile);
02616 
02617     default:
02618       return CalcClosestTownFromTile(tile, threshold);
02619   }
02620 }
02621 
02622 static bool _town_rating_test = false;
02623 SmallMap<const Town *, int, 4> _town_test_ratings;
02624 
02625 void SetTownRatingTestMode(bool mode)
02626 {
02627   static int ref_count = 0;
02628   if (mode) {
02629     if (ref_count == 0) {
02630       _town_test_ratings.Clear();
02631     }
02632     ref_count++;
02633   } else {
02634     assert(ref_count > 0);
02635     ref_count--;
02636   }
02637   _town_rating_test = !(ref_count == 0);
02638 }
02639 
02640 static int GetRating(const Town *t)
02641 {
02642   if (_town_rating_test) {
02643     SmallMap<const Town *, int>::iterator it = _town_test_ratings.Find(t);
02644     if (it != _town_test_ratings.End()) {
02645       return it->second;
02646     }
02647   }
02648   return t->ratings[_current_company];
02649 }
02650 
02658 void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
02659 {
02660   /* if magic_bulldozer cheat is active, town doesn't penaltize for removing stuff */
02661   if (t == NULL || (flags & DC_NO_MODIFY_TOWN_RATING) ||
02662       !IsValidCompanyID(_current_company) ||
02663       (_cheats.magic_bulldozer.value && add < 0)) {
02664     return;
02665   }
02666 
02667   int rating = GetRating(t);
02668   if (add < 0) {
02669     if (rating > max) {
02670       rating += add;
02671       if (rating < max) rating = max;
02672     }
02673   } else {
02674     if (rating < max) {
02675       rating += add;
02676       if (rating > max) rating = max;
02677     }
02678   }
02679   if (_town_rating_test) {
02680     _town_test_ratings[t] = rating;
02681   } else {
02682     SetBit(t->have_ratings, _current_company);
02683     t->ratings[_current_company] = rating;
02684     InvalidateWindow(WC_TOWN_AUTHORITY, t->index);
02685   }
02686 }
02687 
02688 /* penalty for removing town-owned stuff */
02689 static const int _default_rating_settings [3][3] = {
02690   /* ROAD_REMOVE, TUNNELBRIDGE_REMOVE, INDUSTRY_REMOVE */
02691   {  0, 128, 384}, // Permissive
02692   { 48, 192, 480}, // Neutral
02693   { 96, 384, 768}, // Hostile
02694 };
02695 
02696 bool CheckforTownRating(DoCommandFlag flags, Town *t, byte type)
02697 {
02698   /* if magic_bulldozer cheat is active, town doesn't restrict your destructive actions */
02699   if (t == NULL || !IsValidCompanyID(_current_company) || _cheats.magic_bulldozer.value)
02700     return true;
02701 
02702   /* check if you're allowed to remove the street/bridge/tunnel/industry
02703    * owned by a town no removal if rating is lower than ... depends now on
02704    * difficulty setting. Minimum town rating selected by difficulty level
02705    */
02706   int modemod = _default_rating_settings[_settings_game.difficulty.town_council_tolerance][type];
02707 
02708   if (GetRating(t) < 16 + modemod && !(flags & DC_NO_TEST_TOWN_RATING)) {
02709     SetDParam(0, t->index);
02710     _error_message = STR_2009_LOCAL_AUTHORITY_REFUSES;
02711     return false;
02712   }
02713 
02714   return true;
02715 }
02716 
02717 void TownsMonthlyLoop()
02718 {
02719   Town *t;
02720 
02721   FOR_ALL_TOWNS(t) {
02722     if (t->road_build_months != 0) t->road_build_months--;
02723 
02724     if (t->exclusive_counter != 0)
02725       if (--t->exclusive_counter == 0) t->exclusivity = INVALID_COMPANY;
02726 
02727     UpdateTownGrowRate(t);
02728     UpdateTownAmounts(t);
02729     UpdateTownUnwanted(t);
02730   }
02731 }
02732 
02733 void TownsYearlyLoop()
02734 {
02735   /* Increment house ages */
02736   for (TileIndex t = 0; t < MapSize(); t++) {
02737     if (!IsTileType(t, MP_HOUSE)) continue;
02738     IncrementHouseAge(t);
02739   }
02740 }
02741 
02742 void InitializeTowns()
02743 {
02744   /* Clean the town pool and create 1 block in it */
02745   _Town_pool.CleanPool();
02746   _Town_pool.AddBlockToPool();
02747 
02748   memset(_subsidies, 0, sizeof(_subsidies));
02749   for (Subsidy *s = _subsidies; s != endof(_subsidies); s++) {
02750     s->cargo_type = CT_INVALID;
02751   }
02752 
02753   _total_towns = 0;
02754 }
02755 
02756 static CommandCost TerraformTile_Town(TileIndex tile, DoCommandFlag flags, uint z_new, Slope tileh_new)
02757 {
02758   if (AutoslopeEnabled()) {
02759     HouseID house = GetHouseType(tile);
02760     GetHouseNorthPart(house); // modifies house to the ID of the north tile
02761     const HouseSpec *hs = GetHouseSpecs(house);
02762 
02763     /* Here we differ from TTDP by checking TILE_NOT_SLOPED */
02764     if (((hs->building_flags & TILE_NOT_SLOPED) == 0) && !IsSteepSlope(tileh_new) &&
02765       (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) return CommandCost(EXPENSES_CONSTRUCTION, _price.terraform);
02766   }
02767 
02768   return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02769 }
02770 
02772 extern const TileTypeProcs _tile_type_town_procs = {
02773   DrawTile_Town,           // draw_tile_proc
02774   GetSlopeZ_Town,          // get_slope_z_proc
02775   ClearTile_Town,          // clear_tile_proc
02776   GetAcceptedCargo_Town,   // get_accepted_cargo_proc
02777   GetTileDesc_Town,        // get_tile_desc_proc
02778   GetTileTrackStatus_Town, // get_tile_track_status_proc
02779   NULL,                    // click_tile_proc
02780   AnimateTile_Town,        // animate_tile_proc
02781   TileLoop_Town,           // tile_loop_clear
02782   ChangeTileOwner_Town,    // change_tile_owner_clear
02783   GetProducedCargo_Town,   // get_produced_cargo_proc
02784   NULL,                    // vehicle_enter_tile_proc
02785   GetFoundation_Town,      // get_foundation_proc
02786   TerraformTile_Town,      // terraform_tile_proc
02787 };
02788 
02789 void ResetHouses()
02790 {
02791   memset(&_house_specs, 0, sizeof(_house_specs));
02792   memcpy(&_house_specs, &_original_house_specs, sizeof(_original_house_specs));
02793 
02794   /* Reset any overrides that have been set. */
02795   _house_mngr.ResetOverride();
02796 }

Generated on Thu Sep 24 19:35:07 2009 for OpenTTD by  doxygen 1.5.6