00001
00002
00005 #include "stdafx.h"
00006 #include "openttd.h"
00007 #include "road_type.h"
00008 #include "road_internal.h"
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 "cheat_type.h"
00041 #include "functions.h"
00042 #include "animated_tile_func.h"
00043 #include "date_func.h"
00044 #include "core/smallmap_type.hpp"
00045
00046 #include "table/strings.h"
00047 #include "table/town_land.h"
00048
00049 uint _total_towns;
00050 HouseSpec _house_specs[HOUSE_MAX];
00051
00052 Town *_cleared_town;
00053 int _cleared_town_rating;
00054
00055
00056 DEFINE_OLD_POOL_GENERIC(Town, Town)
00057
00058 Town::Town(TileIndex tile)
00059 {
00060 if (tile != INVALID_TILE) _total_towns++;
00061 this->xy = tile;
00062 }
00063
00064 Town::~Town()
00065 {
00066 free(this->name);
00067
00068 if (CleaningPool()) return;
00069
00070 Industry *i;
00071
00072
00073
00074 DeleteWindowById(WC_TOWN_VIEW, this->index);
00075 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
00076 _total_towns--;
00077
00078
00079 FOR_ALL_INDUSTRIES(i) if (i->town == this) delete i;
00080
00081
00082 for (TileIndex tile = 0; tile < MapSize(); ++tile) {
00083 switch (GetTileType(tile)) {
00084 case MP_HOUSE:
00085 if (GetTownByTile(tile) == this) DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
00086 break;
00087
00088 case MP_ROAD:
00089
00090 if (HasTownOwnedRoad(tile) && GetTownIndex(tile) == this->index) {
00091 DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
00092 }
00093 break;
00094
00095 case MP_TUNNELBRIDGE:
00096 if (IsTileOwner(tile, OWNER_TOWN) &&
00097 ClosestTownFromTile(tile, UINT_MAX) == this)
00098 DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
00099 break;
00100
00101 default:
00102 break;
00103 }
00104 }
00105
00106 DeleteSubsidyWithTown(this->index);
00107
00108 MarkWholeScreenDirty();
00109
00110 this->xy = INVALID_TILE;
00111
00112 UpdateNearestTownForRoadTiles(false);
00113 }
00114
00118 void Town::InitializeLayout(TownLayout layout)
00119 {
00120 if (layout != TL_RANDOM) {
00121 this->layout = layout;
00122 return;
00123 }
00124
00125 this->layout = TileHash(TileX(this->xy), TileY(this->xy)) % (NUM_TLS - 1);
00126 }
00127
00128 Money HouseSpec::GetRemovalCost() const
00129 {
00130 return (_price.remove_house * this->removal_cost) >> 8;
00131 }
00132
00133
00134 static int _grow_town_result;
00135
00136
00137 enum TownGrowthResult {
00138 GROWTH_SUCCEED = -1,
00139 GROWTH_SEARCH_STOPPED = 0
00140
00141 };
00142
00143 static bool BuildTownHouse(Town *t, TileIndex tile);
00144
00145 static void TownDrawHouseLift(const TileInfo *ti)
00146 {
00147 AddChildSpriteScreen(SPR_LIFT, PAL_NONE, 14, 60 - GetLiftPosition(ti->tile));
00148 }
00149
00150 typedef void TownDrawTileProc(const TileInfo *ti);
00151 static TownDrawTileProc *const _town_draw_tile_procs[1] = {
00152 TownDrawHouseLift
00153 };
00154
00160 static inline DiagDirection RandomDiagDir()
00161 {
00162 return (DiagDirection)(3 & Random());
00163 }
00164
00170 static void DrawTile_Town(TileInfo *ti)
00171 {
00172 HouseID house_id = GetHouseType(ti->tile);
00173
00174 if (house_id >= NEW_HOUSE_OFFSET) {
00175
00176
00177
00178 if (GetHouseSpecs(house_id)->spritegroup != NULL) {
00179 DrawNewHouseTile(ti, house_id);
00180 return;
00181 } else {
00182 house_id = GetHouseSpecs(house_id)->substitute_id;
00183 }
00184 }
00185
00186
00187 const DrawBuildingsTileStruct *dcts = &_town_draw_tile_data[house_id << 4 | TileHash2Bit(ti->x, ti->y) << 2 | GetHouseBuildingStage(ti->tile)];
00188
00189 if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
00190
00191 DrawGroundSprite(dcts->ground.sprite, dcts->ground.pal);
00192
00193
00194 if (IsInvisibilitySet(TO_HOUSES)) return;
00195
00196
00197 SpriteID image = dcts->building.sprite;
00198 if (image != 0) {
00199 AddSortableSpriteToDraw(image, dcts->building.pal,
00200 ti->x + dcts->subtile_x,
00201 ti->y + dcts->subtile_y,
00202 dcts->width,
00203 dcts->height,
00204 dcts->dz,
00205 ti->z,
00206 IsTransparencySet(TO_HOUSES)
00207 );
00208
00209 if (IsTransparencySet(TO_HOUSES)) return;
00210 }
00211
00212 {
00213 int proc = dcts->draw_proc - 1;
00214
00215 if (proc >= 0) _town_draw_tile_procs[proc](ti);
00216 }
00217 }
00218
00219 static uint GetSlopeZ_Town(TileIndex tile, uint x, uint y)
00220 {
00221 return GetTileMaxZ(tile);
00222 }
00223
00225 static Foundation GetFoundation_Town(TileIndex tile, Slope tileh)
00226 {
00227 return FlatteningFoundation(tileh);
00228 }
00229
00236 static void AnimateTile_Town(TileIndex tile)
00237 {
00238 if (GetHouseType(tile) >= NEW_HOUSE_OFFSET) {
00239 AnimateNewHouseTile(tile);
00240 return;
00241 }
00242
00243 if (_tick_counter & 3) return;
00244
00245
00246
00247
00248
00249 if (!(GetHouseSpecs(GetHouseType(tile))->building_flags & BUILDING_IS_ANIMATED)) {
00250 DeleteAnimatedTile(tile);
00251 return;
00252 }
00253
00254 if (!LiftHasDestination(tile)) {
00255 uint i;
00256
00257
00258
00259
00260
00261 do {
00262 i = RandomRange(7);
00263 } while (i == 1 || i * 6 == GetLiftPosition(tile));
00264
00265 SetLiftDestination(tile, i);
00266 }
00267
00268 int pos = GetLiftPosition(tile);
00269 int dest = GetLiftDestination(tile) * 6;
00270 pos += (pos < dest) ? 1 : -1;
00271 SetLiftPosition(tile, pos);
00272
00273 if (pos == dest) {
00274 HaltLift(tile);
00275 DeleteAnimatedTile(tile);
00276 }
00277
00278 MarkTileDirtyByTile(tile);
00279 }
00280
00287 static bool IsCloseToTown(TileIndex tile, uint dist)
00288 {
00289 const Town *t;
00290
00291 FOR_ALL_TOWNS(t) {
00292 if (DistanceManhattan(tile, t->xy) < dist) return true;
00293 }
00294 return false;
00295 }
00296
00305 static void MarkTownSignDirty(Town *t)
00306 {
00307 MarkAllViewportsDirty(
00308 t->sign.left - 6,
00309 t->sign.top - 3,
00310 t->sign.left + t->sign.width_1 * 4 + 12,
00311 t->sign.top + 45
00312 );
00313 }
00314
00320 void UpdateTownVirtCoord(Town *t)
00321 {
00322 MarkTownSignDirty(t);
00323 Point pt = RemapCoords2(TileX(t->xy) * TILE_SIZE, TileY(t->xy) * TILE_SIZE);
00324 SetDParam(0, t->index);
00325 SetDParam(1, t->population);
00326 UpdateViewportSignPos(&t->sign, pt.x, pt.y - 24,
00327 _settings_client.gui.population_in_label ? STR_TOWN_LABEL_POP : STR_TOWN_LABEL);
00328 MarkTownSignDirty(t);
00329 }
00330
00332 void UpdateAllTownVirtCoords()
00333 {
00334 Town *t;
00335 FOR_ALL_TOWNS(t) {
00336 UpdateTownVirtCoord(t);
00337 }
00338 }
00339
00345 static void ChangePopulation(Town *t, int mod)
00346 {
00347 t->population += mod;
00348 InvalidateWindow(WC_TOWN_VIEW, t->index);
00349 UpdateTownVirtCoord(t);
00350
00351 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
00352 }
00353
00359 uint32 GetWorldPopulation()
00360 {
00361 uint32 pop = 0;
00362 const Town *t;
00363
00364 FOR_ALL_TOWNS(t) pop += t->population;
00365 return pop;
00366 }
00367
00372 static void MakeSingleHouseBigger(TileIndex tile)
00373 {
00374 assert(IsTileType(tile, MP_HOUSE));
00375
00376
00377 if (LiftHasDestination(tile)) return;
00378
00379
00380 IncHouseConstructionTick(tile);
00381 if (GetHouseConstructionTick(tile) != 0) return;
00382
00383 const HouseSpec *hs = GetHouseSpecs(GetHouseType(tile));
00384
00385
00386 if (HasBit(hs->callback_mask, CBM_HOUSE_CONSTRUCTION_STATE_CHANGE)) {
00387 uint16 callback_res = GetHouseCallback(CBID_HOUSE_CONSTRUCTION_STATE_CHANGE, 0, 0, GetHouseType(tile), GetTownByTile(tile), tile);
00388 if (callback_res != CALLBACK_FAILED) ChangeHouseAnimationFrame(hs->grffile, tile, callback_res);
00389 }
00390
00391 if (IsHouseCompleted(tile)) {
00392
00393
00394 ChangePopulation(GetTownByTile(tile), hs->population);
00395 ResetHouseAge(tile);
00396 }
00397 MarkTileDirtyByTile(tile);
00398 }
00399
00403 static void MakeTownHouseBigger(TileIndex tile)
00404 {
00405 uint flags = GetHouseSpecs(GetHouseType(tile))->building_flags;
00406 if (flags & BUILDING_HAS_1_TILE) MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 0));
00407 if (flags & BUILDING_2_TILES_Y) MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 1));
00408 if (flags & BUILDING_2_TILES_X) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 0));
00409 if (flags & BUILDING_HAS_4_TILES) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 1));
00410 }
00411
00418 static void TileLoop_Town(TileIndex tile)
00419 {
00420 HouseID house_id = GetHouseType(tile);
00421
00422
00423
00424 if (house_id >= NEW_HOUSE_OFFSET && !NewHouseTileLoop(tile)) return;
00425
00426 if (!IsHouseCompleted(tile)) {
00427
00428 MakeTownHouseBigger(tile);
00429 return;
00430 }
00431
00432 const HouseSpec *hs = GetHouseSpecs(house_id);
00433
00434
00435 if ((hs->building_flags & BUILDING_IS_ANIMATED) &&
00436 house_id < NEW_HOUSE_OFFSET &&
00437 !LiftHasDestination(tile) &&
00438 Chance16(1, 2)) {
00439 AddAnimatedTile(tile);
00440 }
00441
00442 Town *t = GetTownByTile(tile);
00443 uint32 r = Random();
00444
00445 if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
00446 for (uint i = 0; i < 256; i++) {
00447 uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, r, house_id, t, tile);
00448
00449 if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
00450
00451 CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grffile);
00452 if (cargo == CT_INVALID) continue;
00453
00454 uint amt = GB(callback, 0, 8);
00455 uint moved = MoveGoodsToStation(tile, 1, 1, cargo, amt);
00456
00457 const CargoSpec *cs = GetCargo(cargo);
00458 switch (cs->town_effect) {
00459 case TE_PASSENGERS:
00460 t->new_max_pass += amt;
00461 t->new_act_pass += moved;
00462 break;
00463
00464 case TE_MAIL:
00465 t->new_max_mail += amt;
00466 t->new_act_mail += moved;
00467 break;
00468
00469 default:
00470 break;
00471 }
00472 }
00473 } else {
00474 if (GB(r, 0, 8) < hs->population) {
00475 uint amt = GB(r, 0, 8) / 8 + 1;
00476
00477 if (_economy.fluct <= 0) amt = (amt + 1) >> 1;
00478 t->new_max_pass += amt;
00479 t->new_act_pass += MoveGoodsToStation(tile, 1, 1, CT_PASSENGERS, amt);
00480 }
00481
00482 if (GB(r, 8, 8) < hs->mail_generation) {
00483 uint amt = GB(r, 8, 8) / 8 + 1;
00484
00485 if (_economy.fluct <= 0) amt = (amt + 1) >> 1;
00486 t->new_max_mail += amt;
00487 t->new_act_mail += MoveGoodsToStation(tile, 1, 1, CT_MAIL, amt);
00488 }
00489 }
00490
00491 _current_company = OWNER_TOWN;
00492
00493 if (hs->building_flags & BUILDING_HAS_1_TILE &&
00494 HasBit(t->flags12, TOWN_IS_FUNDED) &&
00495 CanDeleteHouse(tile) &&
00496 GetHouseAge(tile) >= hs->minimum_life &&
00497 --t->time_until_rebuild == 0) {
00498 t->time_until_rebuild = GB(r, 16, 8) + 192;
00499
00500 ClearTownHouse(t, tile);
00501
00502
00503 if (GB(r, 24, 8) >= 12) BuildTownHouse(t, tile);
00504 }
00505
00506 _current_company = OWNER_NONE;
00507 }
00508
00513 static bool ClickTile_Town(TileIndex tile)
00514 {
00515
00516 return false;
00517 }
00518
00519 static CommandCost ClearTile_Town(TileIndex tile, DoCommandFlag flags)
00520 {
00521 if (flags & DC_AUTO) return_cmd_error(STR_2004_BUILDING_MUST_BE_DEMOLISHED);
00522 if (!CanDeleteHouse(tile)) return CMD_ERROR;
00523
00524 const HouseSpec *hs = GetHouseSpecs(GetHouseType(tile));
00525
00526 CommandCost cost(EXPENSES_CONSTRUCTION);
00527 cost.AddCost(hs->GetRemovalCost());
00528
00529 int rating = hs->remove_rating_decrease;
00530 _cleared_town_rating += rating;
00531 Town *t = _cleared_town = GetTownByTile(tile);
00532
00533 if (IsValidCompanyID(_current_company)) {
00534 if (rating > t->ratings[_current_company] && !(flags & DC_NO_TEST_TOWN_RATING) && !_cheats.magic_bulldozer.value) {
00535 SetDParam(0, t->index);
00536 return_cmd_error(STR_2009_LOCAL_AUTHORITY_REFUSES);
00537 }
00538 }
00539
00540 ChangeTownRating(t, -rating, RATING_HOUSE_MINIMUM, flags);
00541 if (flags & DC_EXEC) {
00542 ClearTownHouse(t, tile);
00543 }
00544
00545 return cost;
00546 }
00547
00548 static void GetProducedCargo_Town(TileIndex tile, CargoID *b)
00549 {
00550 HouseID house_id = GetHouseType(tile);
00551 const HouseSpec *hs = GetHouseSpecs(house_id);
00552 Town *t = GetTownByTile(tile);
00553
00554 if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
00555 for (uint i = 0; i < 256; i++) {
00556 uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, 0, house_id, t, tile);
00557
00558 if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
00559
00560 CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grffile);
00561
00562 if (cargo == CT_INVALID) continue;
00563 *(b++) = cargo;
00564 }
00565 } else {
00566 if (hs->population > 0) {
00567 *(b++) = CT_PASSENGERS;
00568 }
00569 if (hs->mail_generation > 0) {
00570 *(b++) = CT_MAIL;
00571 }
00572 }
00573 }
00574
00575 static void GetAcceptedCargo_Town(TileIndex tile, AcceptedCargo ac)
00576 {
00577 const HouseSpec *hs = GetHouseSpecs(GetHouseType(tile));
00578 CargoID accepts[3];
00579
00580
00581 for (uint8 i = 0; i < lengthof(accepts); i++) {
00582 accepts[i] = hs->accepts_cargo[i];
00583 }
00584
00585
00586 if (HasBit(hs->callback_mask, CBM_HOUSE_ACCEPT_CARGO)) {
00587 uint16 callback = GetHouseCallback(CBID_HOUSE_ACCEPT_CARGO, 0, 0, GetHouseType(tile), GetTownByTile(tile), tile);
00588 if (callback != CALLBACK_FAILED) {
00589
00590 accepts[0] = GetCargoTranslation(GB(callback, 0, 5), hs->grffile);
00591 accepts[1] = GetCargoTranslation(GB(callback, 5, 5), hs->grffile);
00592 accepts[2] = GetCargoTranslation(GB(callback, 10, 5), hs->grffile);
00593 }
00594 }
00595
00596
00597 if (HasBit(hs->callback_mask, CBM_HOUSE_CARGO_ACCEPTANCE)) {
00598 uint16 callback = GetHouseCallback(CBID_HOUSE_CARGO_ACCEPTANCE, 0, 0, GetHouseType(tile), GetTownByTile(tile), tile);
00599 if (callback != CALLBACK_FAILED) {
00600 if (accepts[0] != CT_INVALID) ac[accepts[0]] = GB(callback, 0, 4);
00601 if (accepts[1] != CT_INVALID) ac[accepts[1]] = GB(callback, 4, 4);
00602 if (_settings_game.game_creation.landscape != LT_TEMPERATE && HasBit(callback, 12)) {
00603
00604 ac[CT_FOOD] = GB(callback, 8, 4);
00605 } else {
00606 if (accepts[2] != CT_INVALID) ac[accepts[2]] = GB(callback, 8, 4);
00607 }
00608 return;
00609 }
00610 }
00611
00612
00613 for (uint8 i = 0; i < lengthof(accepts); i++) {
00614 if (accepts[i] != CT_INVALID) ac[accepts[i]] = hs->cargo_acceptance[i];
00615 }
00616 }
00617
00618 static void GetTileDesc_Town(TileIndex tile, TileDesc *td)
00619 {
00620 const HouseID house = GetHouseType(tile);
00621 const HouseSpec *hs = GetHouseSpecs(house);
00622 bool house_completed = IsHouseCompleted(tile);
00623
00624 td->str = hs->building_name;
00625
00626 uint16 callback_res = GetHouseCallback(CBID_HOUSE_CUSTOM_NAME, house_completed ? 1 : 0, 0, house, GetTownByTile(tile), tile);
00627 if (callback_res != CALLBACK_FAILED) {
00628 StringID new_name = GetGRFStringID(hs->grffile->grfid, 0xD000 + callback_res);
00629 if (new_name != STR_NULL && new_name != STR_UNDEFINED) {
00630 td->str = new_name;
00631 }
00632 }
00633
00634 if (!house_completed) {
00635 SetDParamX(td->dparam, 0, td->str);
00636 td->str = STR_2058_UNDER_CONSTRUCTION;
00637 }
00638
00639 if (hs->grffile != NULL) {
00640 const GRFConfig *gc = GetGRFConfig(hs->grffile->grfid);
00641 td->grf = gc->name;
00642 }
00643
00644 td->owner[0] = OWNER_TOWN;
00645 }
00646
00647 static TrackStatus GetTileTrackStatus_Town(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
00648 {
00649
00650 return 0;
00651 }
00652
00653 static void ChangeTileOwner_Town(TileIndex tile, Owner old_owner, Owner new_owner)
00654 {
00655
00656 }
00657
00658 static bool GrowTown(Town *t);
00659
00660 static void TownTickHandler(Town *t)
00661 {
00662 if (HasBit(t->flags12, TOWN_IS_FUNDED)) {
00663 int i = t->grow_counter - 1;
00664 if (i < 0) {
00665 if (GrowTown(t)) {
00666 i = t->growth_rate;
00667 } else {
00668 i = 0;
00669 }
00670 }
00671 t->grow_counter = i;
00672 }
00673
00674 UpdateTownRadius(t);
00675 }
00676
00677 void OnTick_Town()
00678 {
00679 if (_game_mode == GM_EDITOR) return;
00680
00681
00682
00683 for (_cur_town_iter += GetMaxTownIndex() + 1;
00684 _cur_town_iter >= TOWN_GROWTH_FREQUENCY;
00685 _cur_town_iter -= TOWN_GROWTH_FREQUENCY) {
00686 uint32 i = _cur_town_ctr;
00687
00688 if (++_cur_town_ctr > GetMaxTownIndex())
00689 _cur_town_ctr = 0;
00690
00691 if (IsValidTownID(i)) TownTickHandler(GetTown(i));
00692 }
00693 }
00694
00703 static RoadBits GetTownRoadBits(TileIndex tile)
00704 {
00705 TrackBits b = GetAnyRoadTrackBits(tile, ROADTYPE_ROAD);
00706 RoadBits r = ROAD_NONE;
00707
00708 if (b == TRACK_BIT_NONE) return r;
00709 if (b & TRACK_BIT_X) r |= ROAD_X;
00710 if (b & TRACK_BIT_Y) r |= ROAD_Y;
00711 if (b & TRACK_BIT_UPPER) r |= ROAD_NE | ROAD_NW;
00712 if (b & TRACK_BIT_LOWER) r |= ROAD_SE | ROAD_SW;
00713 if (b & TRACK_BIT_LEFT) r |= ROAD_NW | ROAD_SW;
00714 if (b & TRACK_BIT_RIGHT) r |= ROAD_NE | ROAD_SE;
00715 return r;
00716 }
00717
00728 static bool IsNeighborRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
00729 {
00730 if (!IsValidTile(tile)) return false;
00731
00732
00733 const TileIndexDiff tid_lt[3] = {
00734 TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90RIGHT)),
00735 TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90LEFT)),
00736 TileOffsByDiagDir(ReverseDiagDir(dir)),
00737 };
00738
00739 dist_multi = (dist_multi + 1) * 4;
00740 for (uint pos = 4; pos < dist_multi; pos++) {
00741
00742 TileIndexDiff cur = tid_lt[(pos & 1) ? 0 : 1] * (pos / 4);
00743
00744
00745 if (pos & 2) cur += tid_lt[2];
00746
00747
00748 if (IsValidTile(tile + cur) &&
00749 GetTownRoadBits(TILE_ADD(tile, cur)) & DiagDirToRoadBits((pos & 2) ? dir : ReverseDiagDir(dir))) return true;
00750 }
00751 return false;
00752 }
00753
00762 static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
00763 {
00764 if (TileX(tile) < 2 || TileX(tile) >= MapMaxX() || TileY(tile) < 2 || TileY(tile) >= MapMaxY()) return false;
00765
00766 Slope cur_slope, desired_slope;
00767
00768 for (;;) {
00769
00770 if (GetTownRoadBits(tile) == ROAD_NONE) {
00771
00772
00773
00774 if (CmdFailed(DoCommand(tile, ((dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? ROAD_X : ROAD_Y), 0, DC_AUTO, CMD_BUILD_ROAD)) &&
00775 CmdFailed(DoCommand(tile, 0, 0, DC_AUTO, CMD_LANDSCAPE_CLEAR)))
00776 return false;
00777 }
00778
00779 cur_slope = _settings_game.construction.build_on_slopes ? GetFoundationSlope(tile, NULL) : GetTileSlope(tile, NULL);
00780 if (cur_slope == SLOPE_FLAT) {
00781 no_slope:
00782
00783 switch (t->layout) {
00784 default: NOT_REACHED();
00785
00786 case TL_ORIGINAL:
00787 return !IsNeighborRoadTile(tile, dir, 1);
00788
00789 case TL_BETTER_ROADS:
00790 return !IsNeighborRoadTile(tile, dir, 2);
00791 }
00792 }
00793
00794
00795
00796 desired_slope = (dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? SLOPE_NW : SLOPE_NE;
00797 if (desired_slope != cur_slope && ComplementSlope(desired_slope) != cur_slope) {
00798 if (Chance16(1, 8)) {
00799 CommandCost res = CMD_ERROR;
00800 if (!_generating_world && Chance16(1, 10)) {
00801
00802 res = DoCommand(tile, Chance16(1, 16) ? cur_slope : cur_slope ^ SLOPE_ELEVATED, 0,
00803 DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
00804 }
00805 if (CmdFailed(res) && Chance16(1, 3)) {
00806
00807 goto no_slope;
00808 }
00809 }
00810 return false;
00811 }
00812 return true;
00813 }
00814 }
00815
00816 static bool TerraformTownTile(TileIndex tile, int edges, int dir)
00817 {
00818 TILE_ASSERT(tile);
00819
00820 CommandCost r = DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
00821 if (CmdFailed(r) || r.GetCost() >= (_price.terraform + 2) * 8) return false;
00822 DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER | DC_EXEC, CMD_TERRAFORM_LAND);
00823 return true;
00824 }
00825
00826 static void LevelTownLand(TileIndex tile)
00827 {
00828 TILE_ASSERT(tile);
00829
00830
00831 if (IsTileType(tile, MP_HOUSE)) return;
00832 Slope tileh = GetTileSlope(tile, NULL);
00833 if (tileh == SLOPE_FLAT) return;
00834
00835
00836 if (!TerraformTownTile(tile, ~tileh & SLOPE_ELEVATED, 1)) {
00837 TerraformTownTile(tile, tileh & SLOPE_ELEVATED, 0);
00838 }
00839 }
00840
00850 static RoadBits GetTownRoadGridElement(Town *t, TileIndex tile, DiagDirection dir)
00851 {
00852
00853 TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
00854 RoadBits rcmd = ROAD_NONE;
00855
00856 switch (t->layout) {
00857 default: NOT_REACHED();
00858
00859 case TL_2X2_GRID:
00860 if ((grid_pos.x % 3) == 0) rcmd |= ROAD_Y;
00861 if ((grid_pos.y % 3) == 0) rcmd |= ROAD_X;
00862 break;
00863
00864 case TL_3X3_GRID:
00865 if ((grid_pos.x % 4) == 0) rcmd |= ROAD_Y;
00866 if ((grid_pos.y % 4) == 0) rcmd |= ROAD_X;
00867 break;
00868 }
00869
00870
00871 if (rcmd != ROAD_ALL) return rcmd;
00872
00873 RoadBits rb_template;
00874
00875 switch (GetTileSlope(tile, NULL)) {
00876 default: rb_template = ROAD_ALL; break;
00877 case SLOPE_W: rb_template = ROAD_NW | ROAD_SW; break;
00878 case SLOPE_SW: rb_template = ROAD_Y | ROAD_SW; break;
00879 case SLOPE_S: rb_template = ROAD_SW | ROAD_SE; break;
00880 case SLOPE_SE: rb_template = ROAD_X | ROAD_SE; break;
00881 case SLOPE_E: rb_template = ROAD_SE | ROAD_NE; break;
00882 case SLOPE_NE: rb_template = ROAD_Y | ROAD_NE; break;
00883 case SLOPE_N: rb_template = ROAD_NE | ROAD_NW; break;
00884 case SLOPE_NW: rb_template = ROAD_X | ROAD_NW; break;
00885 case SLOPE_STEEP_W:
00886 case SLOPE_STEEP_S:
00887 case SLOPE_STEEP_E:
00888 case SLOPE_STEEP_N:
00889 rb_template = ROAD_NONE;
00890 break;
00891 }
00892
00893
00894 if (DiagDirToRoadBits(ReverseDiagDir(dir)) & rb_template) return rb_template;
00895
00896 return DiagDirToRoadBits(dir) | DiagDirToRoadBits(ReverseDiagDir(dir));
00897 }
00898
00909 static bool GrowTownWithExtraHouse(Town *t, TileIndex tile)
00910 {
00911
00912 if (TileX(tile) < 2 || TileY(tile) < 2 || MapMaxX() <= TileX(tile) || MapMaxY() <= TileY(tile)) return false;
00913
00914 uint counter = 0;
00915
00916
00917 for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
00918
00919 if (IsTileType(TileAddByDiagDir(tile, dir), MP_HOUSE)) counter++;
00920
00921
00922 if (counter >= 3) {
00923 if (BuildTownHouse(t, tile)) {
00924 _grow_town_result = GROWTH_SUCCEED;
00925 return true;
00926 }
00927 return false;
00928 }
00929 }
00930 return false;
00931 }
00932
00941 static bool GrowTownWithRoad(const Town *t, TileIndex tile, RoadBits rcmd)
00942 {
00943 if (CmdSucceeded(DoCommand(tile, rcmd, t->index, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD))) {
00944 _grow_town_result = GROWTH_SUCCEED;
00945 return true;
00946 }
00947 return false;
00948 }
00949
00960 static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
00961 {
00962 assert(bridge_dir < DIAGDIR_END);
00963
00964 const Slope slope = GetTileSlope(tile, NULL);
00965 if (slope == SLOPE_FLAT) return false;
00966
00967
00968
00969
00970 if (HASBITS(slope, InclinedSlope(bridge_dir))) return false;
00971
00972
00973 if (!(GetTownRoadBits(TileAddByDiagDir(tile, ReverseDiagDir(bridge_dir))) & DiagDirToRoadBits(bridge_dir))) return false;
00974
00975
00976 uint8 bridge_length = 0;
00977 TileIndex bridge_tile = tile;
00978
00979 const int delta = TileOffsByDiagDir(bridge_dir);
00980 do {
00981 if (bridge_length++ >= 11) {
00982
00983 return false;
00984 }
00985 bridge_tile += delta;
00986 } while (TileX(bridge_tile) != 0 && TileY(bridge_tile) != 0 && IsWaterTile(bridge_tile));
00987
00988
00989 if (bridge_length == 1) return false;
00990
00991 for (uint8 times = 0; times <= 22; times++) {
00992 byte bridge_type = RandomRange(MAX_BRIDGES - 1);
00993
00994
00995 if (CmdSucceeded(DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, DC_AUTO, CMD_BUILD_BRIDGE))) {
00996 DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, DC_EXEC | DC_AUTO, CMD_BUILD_BRIDGE);
00997 _grow_town_result = GROWTH_SUCCEED;
00998 return true;
00999 }
01000 }
01001
01002 return false;
01003 }
01004
01022 static void GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1)
01023 {
01024 RoadBits rcmd = ROAD_NONE;
01025 TileIndex tile = *tile_ptr;
01026
01027 TILE_ASSERT(tile);
01028
01029 if (cur_rb == ROAD_NONE) {
01030
01031
01032 _grow_town_result = GROWTH_SEARCH_STOPPED;
01033
01034 if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
01035
01036
01037 if (!_settings_game.construction.build_on_slopes || Chance16(1, 6)) LevelTownLand(tile);
01038
01039
01040 switch (t1->layout) {
01041 default: NOT_REACHED();
01042
01043 case TL_3X3_GRID:
01044 case TL_2X2_GRID:
01045 rcmd = GetTownRoadGridElement(t1, tile, target_dir);
01046 if (rcmd == ROAD_NONE) return;
01047 break;
01048
01049 case TL_BETTER_ROADS:
01050 case TL_ORIGINAL:
01051 if (!IsRoadAllowedHere(t1, tile, target_dir)) return;
01052
01053 DiagDirection source_dir = ReverseDiagDir(target_dir);
01054
01055 if (Chance16(1, 4)) {
01056
01057 do target_dir = RandomDiagDir(); while (target_dir == source_dir);
01058 }
01059
01060 if (!IsRoadAllowedHere(t1, TileAddByDiagDir(tile, target_dir), target_dir)) {
01061
01062
01063 if (target_dir != ReverseDiagDir(source_dir)) return;
01064
01065
01066 if (!IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90RIGHT)), MP_HOUSE) &&
01067 !IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90LEFT)), MP_HOUSE)) {
01068 return;
01069 }
01070
01071
01072
01073 }
01074
01075 rcmd = DiagDirToRoadBits(target_dir) | DiagDirToRoadBits(source_dir);
01076 break;
01077 }
01078
01079 } else if (target_dir < DIAGDIR_END && !(cur_rb & DiagDirToRoadBits(ReverseDiagDir(target_dir)))) {
01080
01081
01082
01083 _grow_town_result = GROWTH_SEARCH_STOPPED;
01084
01085 if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
01086
01087 switch (t1->layout) {
01088 default: NOT_REACHED();
01089
01090 case TL_3X3_GRID:
01091 case TL_2X2_GRID:
01092 rcmd = GetTownRoadGridElement(t1, tile, target_dir);
01093 break;
01094
01095 case TL_BETTER_ROADS:
01096 case TL_ORIGINAL:
01097 rcmd = DiagDirToRoadBits(ReverseDiagDir(target_dir));
01098 break;
01099 }
01100 } else {
01101 bool allow_house = true;
01102
01103
01104 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
01105 if (GetTunnelBridgeTransportType(tile) == TRANSPORT_ROAD) {
01106 *tile_ptr = GetOtherTunnelBridgeEnd(tile);
01107 }
01108 return;
01109 }
01110
01111
01112
01113 target_dir = RandomDiagDir();
01114 if (cur_rb & DiagDirToRoadBits(target_dir)) return;
01115
01116
01117 TileIndex house_tile = TileAddByDiagDir(tile, target_dir);
01118
01119
01120 if (IsWaterTile(house_tile)) return;
01121
01122 if (!IsValidTile(house_tile) || !IsValidTile(house_tile + TileOffsByDiagDir(target_dir))) return;
01123
01124 if (_settings_game.economy.allow_town_roads || _generating_world) {
01125 switch (t1->layout) {
01126 default: NOT_REACHED();
01127
01128 case TL_3X3_GRID:
01129 GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
01130
01131
01132 case TL_2X2_GRID:
01133 rcmd = GetTownRoadGridElement(t1, house_tile, target_dir);
01134 allow_house = (rcmd == ROAD_NONE);
01135 break;
01136
01137 case TL_BETTER_ROADS:
01138 GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
01139
01140
01141 case TL_ORIGINAL:
01142
01143
01144 rcmd = DiagDirToRoadBits(target_dir);
01145 allow_house = (!IsRoadAllowedHere(t1, house_tile, target_dir) || Chance16(6, 10));
01146 break;
01147 }
01148 }
01149
01150 if (allow_house) {
01151
01152 if (!IsTileType(house_tile, MP_HOUSE)) {
01153
01154 if (Chance16(1, 6)) LevelTownLand(house_tile);
01155
01156
01157
01158 if (BuildTownHouse(t1, house_tile)) {
01159 _grow_town_result = GROWTH_SUCCEED;
01160 }
01161 }
01162 return;
01163 }
01164
01165 _grow_town_result = GROWTH_SEARCH_STOPPED;
01166 }
01167
01168
01169 if (IsWaterTile(tile)) return;
01170
01171
01172 rcmd = CleanUpRoadBits(tile, rcmd);
01173 if (rcmd == ROAD_NONE) return;
01174
01175
01176
01177
01178 if (GrowTownWithBridge(t1, tile, target_dir)) return;
01179
01180 GrowTownWithRoad(t1, tile, rcmd);
01181 }
01182
01188 static int GrowTownAtRoad(Town *t, TileIndex tile)
01189 {
01190
01191
01192
01193 DiagDirection target_dir = DIAGDIR_END;
01194
01195 TILE_ASSERT(tile);
01196
01197
01198
01199
01200 switch (t->layout) {
01201 case TL_BETTER_ROADS:
01202 _grow_town_result = 10 + t->num_houses * 2 / 9;
01203 break;
01204
01205 case TL_3X3_GRID:
01206 case TL_2X2_GRID:
01207 _grow_town_result = 10 + t->num_houses * 1 / 9;
01208 break;
01209
01210 default:
01211 _grow_town_result = 10 + t->num_houses * 4 / 9;
01212 break;
01213 }
01214
01215 do {
01216 RoadBits cur_rb = GetTownRoadBits(tile);
01217
01218
01219 GrowTownInTile(&tile, cur_rb, target_dir, t);
01220
01221
01222
01223 cur_rb &= ~DiagDirToRoadBits(ReverseDiagDir(target_dir));
01224 if (cur_rb == ROAD_NONE)
01225 return _grow_town_result;
01226
01227
01228
01229 do target_dir = RandomDiagDir(); while (!(cur_rb & DiagDirToRoadBits(target_dir)));
01230 tile = TileAddByDiagDir(tile, target_dir);
01231
01232 if (IsTileType(tile, MP_ROAD) && !IsRoadDepot(tile) && HasTileRoadType(tile, ROADTYPE_ROAD)) {
01233
01234 if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN) && GetTownByTile(tile) != t) {
01235 _grow_town_result = GROWTH_SUCCEED;
01236 } else if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_NONE) && _game_mode == GM_EDITOR) {
01237
01238
01239 SetRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN);
01240 SetTownIndex(tile, t->index);
01241 }
01242 }
01243
01244
01245 } while (--_grow_town_result >= 0);
01246
01247 return (_grow_town_result == -2);
01248 }
01249
01257 static RoadBits GenRandomRoadBits()
01258 {
01259 uint32 r = Random();
01260 uint a = GB(r, 0, 2);
01261 uint b = GB(r, 8, 2);
01262 if (a == b) b ^= 2;
01263 return (RoadBits)((ROAD_NW << a) + (ROAD_NW << b));
01264 }
01265
01270 static bool GrowTown(Town *t)
01271 {
01272 static const TileIndexDiffC _town_coord_mod[] = {
01273 {-1, 0},
01274 { 1, 1},
01275 { 1, -1},
01276 {-1, -1},
01277 {-1, 0},
01278 { 0, 2},
01279 { 2, 0},
01280 { 0, -2},
01281 {-1, -1},
01282 {-2, 2},
01283 { 2, 2},
01284 { 2, -2},
01285 { 0, 0}
01286 };
01287
01288
01289 CompanyID old_company = _current_company;
01290 _current_company = OWNER_TOWN;
01291
01292 TileIndex tile = t->xy;
01293
01294
01295 const TileIndexDiffC *ptr;
01296 for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
01297 if (GetTownRoadBits(tile) != ROAD_NONE) {
01298 int r = GrowTownAtRoad(t, tile);
01299 _current_company = old_company;
01300 return r != 0;
01301 }
01302 tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
01303 }
01304
01305
01306
01307 tile = t->xy;
01308 for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
01309
01310 if (!IsTileType(tile, MP_HOUSE) && GetTileSlope(tile, NULL) == SLOPE_FLAT) {
01311 if (CmdSucceeded(DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR))) {
01312 DoCommand(tile, GenRandomRoadBits(), t->index, DC_EXEC | DC_AUTO, CMD_BUILD_ROAD);
01313 _current_company = old_company;
01314 return true;
01315 }
01316 }
01317 tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
01318 }
01319
01320 _current_company = old_company;
01321 return false;
01322 }
01323
01324 void UpdateTownRadius(Town *t)
01325 {
01326 static const uint32 _town_squared_town_zone_radius_data[23][5] = {
01327 { 4, 0, 0, 0, 0},
01328 { 16, 0, 0, 0, 0},
01329 { 25, 0, 0, 0, 0},
01330 { 36, 0, 0, 0, 0},
01331 { 49, 0, 4, 0, 0},
01332 { 64, 0, 4, 0, 0},
01333 { 64, 0, 9, 0, 1},
01334 { 64, 0, 9, 0, 4},
01335 { 64, 0, 16, 0, 4},
01336 { 81, 0, 16, 0, 4},
01337 { 81, 0, 16, 0, 4},
01338 { 81, 0, 25, 0, 9},
01339 { 81, 36, 25, 0, 9},
01340 { 81, 36, 25, 16, 9},
01341 { 81, 49, 0, 25, 9},
01342 { 81, 64, 0, 25, 9},
01343 { 81, 64, 0, 36, 9},
01344 { 81, 64, 0, 36, 16},
01345 {100, 81, 0, 49, 16},
01346 {100, 81, 0, 49, 25},
01347 {121, 81, 0, 49, 25},
01348 {121, 81, 0, 49, 25},
01349 {121, 81, 0, 49, 36},
01350 };
01351
01352 if (t->num_houses < 92) {
01353 memcpy(t->squared_town_zone_radius, _town_squared_town_zone_radius_data[t->num_houses / 4], sizeof(t->squared_town_zone_radius));
01354 } else {
01355 int mass = t->num_houses / 8;
01356
01357
01358
01359 t->squared_town_zone_radius[0] = mass * 15 - 40;
01360 t->squared_town_zone_radius[1] = mass * 9 - 15;
01361 t->squared_town_zone_radius[2] = 0;
01362 t->squared_town_zone_radius[3] = mass * 5 - 5;
01363 t->squared_town_zone_radius[4] = mass * 3 + 5;
01364 }
01365 }
01366
01367 static bool CreateTownName(uint32 *townnameparts)
01368 {
01369 extern int _nb_orig_names;
01370 Town *t2;
01371 char buf1[64];
01372 char buf2[64];
01373 uint32 r;
01374
01375
01376
01377
01378
01379 int tries = 1000;
01380 bool grf = (_settings_game.game_creation.town_name >= _nb_orig_names);
01381 uint32 grfid = grf ? GetGRFTownNameId(_settings_game.game_creation.town_name - _nb_orig_names) : 0;
01382 uint16 townnametype = grf ? GetGRFTownNameType(_settings_game.game_creation.town_name - _nb_orig_names) : SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
01383
01384 assert(townnameparts != NULL);
01385
01386 for (;;) {
01387 restart:
01388 r = Random();
01389
01390 SetDParam(0, r);
01391 if (grf && grfid != 0) {
01392 GRFTownNameGenerate(buf1, grfid, townnametype, r, lastof(buf1));
01393 } else {
01394 GetString(buf1, townnametype, lastof(buf1));
01395 }
01396
01397
01398 if (strlen(buf1) >= MAX_LENGTH_TOWN_NAME_BYTES || GetStringBoundingBox(buf1).width > MAX_LENGTH_TOWN_NAME_PIXELS) continue;
01399
01400 FOR_ALL_TOWNS(t2) {
01401
01402
01403 SetDParam(0, t2->index);
01404 GetString(buf2, STR_TOWN, lastof(buf2));
01405 if (strcmp(buf1, buf2) == 0) {
01406 if (tries-- < 0) return false;
01407 goto restart;
01408 }
01409 }
01410 *townnameparts = r;
01411 return true;
01412 }
01413 }
01414
01415 void UpdateTownMaxPass(Town *t)
01416 {
01417 t->max_pass = t->population >> 3;
01418 t->max_mail = t->population >> 4;
01419 }
01420
01430 static void DoCreateTown(Town *t, TileIndex tile, uint32 townnameparts, TownSize size, bool city, TownLayout layout)
01431 {
01432 extern int _nb_orig_names;
01433
01434 t->xy = tile;
01435 t->num_houses = 0;
01436 t->time_until_rebuild = 10;
01437 UpdateTownRadius(t);
01438 t->flags12 = 0;
01439 t->population = 0;
01440 t->grow_counter = 0;
01441 t->growth_rate = 250;
01442 t->new_max_pass = 0;
01443 t->new_max_mail = 0;
01444 t->new_act_pass = 0;
01445 t->new_act_mail = 0;
01446 t->max_pass = 0;
01447 t->max_mail = 0;
01448 t->act_pass = 0;
01449 t->act_mail = 0;
01450
01451 t->pct_pass_transported = 0;
01452 t->pct_mail_transported = 0;
01453 t->fund_buildings_months = 0;
01454 t->new_act_food = 0;
01455 t->new_act_water = 0;
01456 t->act_food = 0;
01457 t->act_water = 0;
01458
01459 for (uint i = 0; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
01460
01461 t->have_ratings = 0;
01462 t->exclusivity = INVALID_COMPANY;
01463 t->exclusive_counter = 0;
01464 t->statues = 0;
01465
01466 if (_settings_game.game_creation.town_name < _nb_orig_names) {
01467
01468 t->townnamegrfid = 0;
01469 t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
01470 } else {
01471
01472 t->townnamegrfid = GetGRFTownNameId(_settings_game.game_creation.town_name - _nb_orig_names);
01473 t->townnametype = GetGRFTownNameType(_settings_game.game_creation.town_name - _nb_orig_names);
01474 }
01475 t->townnameparts = townnameparts;
01476
01477 UpdateTownVirtCoord(t);
01478 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
01479
01480 t->InitializeLayout(layout);
01481
01482 t->larger_town = city;
01483
01484 int x = (int)size * 16 + 3;
01485 if (size == TS_RANDOM) x = (Random() & 0xF) + 8;
01486 if (city) x *= _settings_game.economy.initial_city_size;
01487
01488 t->noise_reached = 0;
01489
01490 t->num_houses += x;
01491 UpdateTownRadius(t);
01492
01493 int i = x * 4;
01494 do {
01495 GrowTown(t);
01496 } while (--i);
01497
01498 t->num_houses -= x;
01499 UpdateTownRadius(t);
01500 UpdateTownMaxPass(t);
01501 }
01502
01513 CommandCost CmdBuildTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01514 {
01515
01516 if (_game_mode != GM_EDITOR) return CMD_ERROR;
01517
01518 TownSize size = (TownSize)GB(p1, 0, 2);
01519 bool city = HasBit(p1, 2);
01520 TownLayout layout = (TownLayout)GB(p1, 3, 3);
01521
01522 if (size > TS_RANDOM) return CMD_ERROR;
01523 if (layout > TL_RANDOM) return CMD_ERROR;
01524
01525
01526 if (DistanceFromEdge(tile) < 12)
01527 return_cmd_error(STR_0237_TOO_CLOSE_TO_EDGE_OF_MAP);
01528
01529
01530 if ((!IsTileType(tile, MP_CLEAR) && !IsTileType(tile, MP_TREES)) || GetTileSlope(tile, NULL) != SLOPE_FLAT) {
01531 return_cmd_error(STR_0239_SITE_UNSUITABLE);
01532 }
01533
01534
01535 if (IsCloseToTown(tile, 20))
01536 return_cmd_error(STR_0238_TOO_CLOSE_TO_ANOTHER_TOWN);
01537
01538 uint32 townnameparts;
01539
01540
01541 if (!CreateTownName(&townnameparts))
01542 return_cmd_error(STR_023A_TOO_MANY_TOWNS);
01543
01544
01545 if (!Town::CanAllocateItem()) return_cmd_error(STR_023A_TOO_MANY_TOWNS);
01546
01547
01548 if (flags & DC_EXEC) {
01549 Town *t = new Town(tile);
01550 _generating_world = true;
01551 UpdateNearestTownForRoadTiles(true);
01552 DoCreateTown(t, tile, townnameparts, size, city, layout);
01553 UpdateNearestTownForRoadTiles(false);
01554 _generating_world = false;
01555 }
01556 return CommandCost();
01557 }
01558
01559 Town *CreateRandomTown(uint attempts, TownSize size, bool city, TownLayout layout)
01560 {
01561 if (!Town::CanAllocateItem()) return NULL;
01562
01563 do {
01564
01565 TileIndex tile = RandomTile();
01566 switch (layout) {
01567 case TL_2X2_GRID:
01568 tile = TileXY(TileX(tile) - TileX(tile) % 3, TileY(tile) - TileY(tile) % 3);
01569 break;
01570 case TL_3X3_GRID:
01571 tile = TileXY(TileX(tile) & ~3, TileY(tile) & ~3);
01572 break;
01573 default: break;
01574 }
01575 if (DistanceFromEdge(tile) < 20) continue;
01576
01577
01578 if (!IsTileType(tile, MP_CLEAR) || GetTileSlope(tile, NULL) != SLOPE_FLAT) continue;
01579
01580
01581 if (IsCloseToTown(tile, 20)) continue;
01582
01583 uint32 townnameparts;
01584
01585
01586 if (!CreateTownName(&townnameparts)) break;
01587
01588
01589 Town *t = new Town(tile);
01590
01591 DoCreateTown(t, tile, townnameparts, size, city, layout);
01592 return t;
01593 } while (--attempts != 0);
01594
01595 return NULL;
01596 }
01597
01598 static const byte _num_initial_towns[4] = {5, 11, 23, 46};
01599
01600 bool GenerateTowns(TownLayout layout)
01601 {
01602 uint num = 0;
01603 uint n = ScaleByMapSize(_num_initial_towns[_settings_game.difficulty.number_towns] + (Random() & 7));
01604 uint num_cities = _settings_game.economy.larger_towns == 0 ? 0 : n / _settings_game.economy.larger_towns;
01605
01606 SetGeneratingWorldProgress(GWP_TOWN, n);
01607
01608 do {
01609 IncreaseGeneratingWorldProgress(GWP_TOWN);
01610
01611 if (CreateRandomTown(20, TS_RANDOM, num_cities > 0, layout) != NULL) num++;
01612 if (num_cities > 0) num_cities--;
01613 } while (--n);
01614
01615
01616 if (num == 0 && CreateRandomTown(10000, TS_RANDOM, false, layout) == NULL) {
01617 if (GetNumTowns() == 0) {
01618
01619 if (_game_mode != GM_EDITOR) usererror("Could not generate any town");
01620
01621 return false;
01622 }
01623 }
01624
01625 return true;
01626 }
01627
01628
01634 HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
01635 {
01636 uint dist = DistanceSquare(tile, t->xy);
01637
01638 if (t->fund_buildings_months && dist <= 25) return HZB_TOWN_CENTRE;
01639
01640 HouseZonesBits smallest = HZB_TOWN_EDGE;
01641 for (HouseZonesBits i = HZB_BEGIN; i < HZB_END; i++) {
01642 if (dist < t->squared_town_zone_radius[i]) smallest = i;
01643 }
01644
01645 return smallest;
01646 }
01647
01658 static inline void ClearMakeHouseTile(TileIndex tile, Town *t, byte counter, byte stage, HouseID type, byte random_bits)
01659 {
01660 CommandCost cc = DoCommand(tile, 0, 0, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR);
01661
01662 assert(CmdSucceeded(cc));
01663
01664 IncreaseBuildingCount(t, type);
01665 MakeHouseTile(tile, t->index, counter, stage, type, random_bits);
01666 if (GetHouseSpecs(type)->building_flags & BUILDING_IS_ANIMATED) AddAnimatedTile(tile);
01667
01668 MarkTileDirtyByTile(tile);
01669 }
01670
01671
01682 static void MakeTownHouse(TileIndex t, Town *town, byte counter, byte stage, HouseID type, byte random_bits)
01683 {
01684 BuildingFlags size = GetHouseSpecs(type)->building_flags;
01685
01686 ClearMakeHouseTile(t, town, counter, stage, type, random_bits);
01687 if (size & BUILDING_2_TILES_Y) ClearMakeHouseTile(t + TileDiffXY(0, 1), town, counter, stage, ++type, random_bits);
01688 if (size & BUILDING_2_TILES_X) ClearMakeHouseTile(t + TileDiffXY(1, 0), town, counter, stage, ++type, random_bits);
01689 if (size & BUILDING_HAS_4_TILES) ClearMakeHouseTile(t + TileDiffXY(1, 1), town, counter, stage, ++type, random_bits);
01690 }
01691
01692
01701 static inline bool CanBuildHouseHere(TileIndex tile, TownID town, bool noslope)
01702 {
01703
01704 Slope slope = GetTileSlope(tile, NULL);
01705 if ((noslope && slope != SLOPE_FLAT) || IsSteepSlope(slope)) return false;
01706
01707
01708 if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return false;
01709
01710
01711 if (IsTileType(tile, MP_HOUSE) && GetTownIndex(tile) != town) return false;
01712
01713
01714 return CmdSucceeded(DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR));
01715 }
01716
01717
01727 static inline bool CheckBuildHouseSameZ(TileIndex tile, TownID town, uint z, bool noslope)
01728 {
01729 if (!CanBuildHouseHere(tile, town, noslope)) return false;
01730
01731
01732 if (GetTileMaxZ(tile) != z) return false;
01733
01734 return true;
01735 }
01736
01737
01747 static bool CheckFree2x2Area(TileIndex tile, TownID town, uint z, bool noslope)
01748 {
01749
01750 if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
01751
01752 for (DiagDirection d = DIAGDIR_SE; d < DIAGDIR_END; d++) {
01753 tile += TileOffsByDiagDir(d);
01754 if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
01755 }
01756
01757 return true;
01758 }
01759
01760
01768 static inline bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile)
01769 {
01770 TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
01771
01772 switch (t->layout) {
01773 case TL_2X2_GRID:
01774 if ((grid_pos.x % 3) == 0 || (grid_pos.y % 3) == 0) return false;
01775 break;
01776
01777 case TL_3X3_GRID:
01778 if ((grid_pos.x % 4) == 0 || (grid_pos.y % 4) == 0) return false;
01779 break;
01780
01781 default:
01782 break;
01783 }
01784
01785 return true;
01786 }
01787
01788
01796 static inline bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile)
01797 {
01798
01799
01800 uint dx = MapSize() + TileX(t->xy) - TileX(tile);
01801 uint dy = MapSize() + TileY(t->xy) - TileY(tile);
01802
01803 switch (t->layout) {
01804 case TL_2X2_GRID:
01805 if ((dx % 3) != 0 || (dy % 3) != 0) return false;
01806 break;
01807
01808 case TL_3X3_GRID:
01809 if ((dx % 4) < 2 || (dy % 4) < 2) return false;
01810 break;
01811
01812 default:
01813 break;
01814 }
01815
01816 return true;
01817 }
01818
01819
01829 static bool CheckTownBuild2House(TileIndex *tile, Town *t, uint maxz, bool noslope, DiagDirection second)
01830 {
01831
01832
01833 TileIndex tile2 = *tile + TileOffsByDiagDir(second);
01834 if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) return true;
01835
01836 tile2 = *tile + TileOffsByDiagDir(ReverseDiagDir(second));
01837 if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) {
01838 *tile = tile2;
01839 return true;
01840 }
01841
01842 return false;
01843 }
01844
01845
01854 static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, uint maxz, bool noslope)
01855 {
01856 TileIndex tile2 = *tile;
01857
01858 for (DiagDirection d = DIAGDIR_SE;;d++) {
01859 if (TownLayoutAllows2x2HouseHere(t, tile2) && CheckFree2x2Area(tile2, t->index, maxz, noslope)) {
01860 *tile = tile2;
01861 return true;
01862 }
01863 if (d == DIAGDIR_END) break;
01864 tile2 += TileOffsByDiagDir(ReverseDiagDir(d));
01865 }
01866
01867 return false;
01868 }
01869
01870
01877 static bool BuildTownHouse(Town *t, TileIndex tile)
01878 {
01879
01880 if (!TownLayoutAllowsHouseHere(t, tile)) return false;
01881
01882
01883 if (!CanBuildHouseHere(tile, t->index, false)) return false;
01884
01885 uint z;
01886 Slope slope = GetTileSlope(tile, &z);
01887
01888
01889
01890 HouseZonesBits rad = GetTownRadiusGroup(t, tile);
01891
01892
01893 int land = _settings_game.game_creation.landscape;
01894 if (land == LT_ARCTIC && z >= _settings_game.game_creation.snow_line) land = -1;
01895
01896 uint bitmask = (1 << rad) + (1 << (land + 12));
01897
01898
01899
01900
01901 HouseID houses[HOUSE_MAX];
01902 uint num = 0;
01903 uint probs[HOUSE_MAX];
01904 uint probability_max = 0;
01905
01906
01907 for (uint i = 0; i < HOUSE_MAX; i++) {
01908 const HouseSpec *hs = GetHouseSpecs(i);
01909
01910 if ((~hs->building_availability & bitmask) == 0 && hs->enabled) {
01911
01912 uint cur_prob = (_loaded_newgrf_features.has_newhouses ? hs->probability : 1);
01913 probability_max += cur_prob;
01914 probs[num] = cur_prob;
01915 houses[num++] = (HouseID)i;
01916 }
01917 }
01918
01919 uint maxz = GetTileMaxZ(tile);
01920
01921 while (probability_max > 0) {
01922 uint r = RandomRange(probability_max);
01923 uint i;
01924 for (i = 0; i < num; i++) {
01925 if (probs[i] > r) break;
01926 r -= probs[i];
01927 }
01928
01929 HouseID house = houses[i];
01930 probability_max -= probs[i];
01931
01932
01933 num--;
01934 houses[i] = houses[num];
01935 probs[i] = probs[num];
01936
01937 const HouseSpec *hs = GetHouseSpecs(house);
01938
01939 if (_loaded_newgrf_features.has_newhouses) {
01940 if (hs->override != 0) {
01941 house = hs->override;
01942 hs = GetHouseSpecs(house);
01943 }
01944
01945 if ((hs->extra_flags & BUILDING_IS_HISTORICAL) && !_generating_world) continue;
01946 }
01947
01948 if (_cur_year < hs->min_year || _cur_year > hs->max_year) continue;
01949
01950
01951 uint oneof = 0;
01952
01953 if (hs->building_flags & BUILDING_IS_CHURCH) {
01954 SetBit(oneof, TOWN_HAS_CHURCH);
01955 } else if (hs->building_flags & BUILDING_IS_STADIUM) {
01956 SetBit(oneof, TOWN_HAS_STADIUM);
01957 }
01958
01959 if (HASBITS(t->flags12, oneof)) continue;
01960
01961
01962 bool noslope = (hs->building_flags & TILE_NOT_SLOPED) != 0;
01963 if (noslope && slope != SLOPE_FLAT) continue;
01964
01965 if (hs->building_flags & TILE_SIZE_2x2) {
01966 if (!CheckTownBuild2x2House(&tile, t, maxz, noslope)) continue;
01967 } else if (hs->building_flags & TILE_SIZE_2x1) {
01968 if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SW)) continue;
01969 } else if (hs->building_flags & TILE_SIZE_1x2) {
01970 if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SE)) continue;
01971 } else {
01972
01973 }
01974
01975 if (HasBit(hs->callback_mask, CBM_HOUSE_ALLOW_CONSTRUCTION)) {
01976 uint16 callback_res = GetHouseCallback(CBID_HOUSE_ALLOW_CONSTRUCTION, 0, 0, house, t, tile);
01977 if (callback_res != CALLBACK_FAILED && GB(callback_res, 0, 8) == 0) continue;
01978 }
01979
01980
01981 t->num_houses++;
01982
01983
01984 t->flags12 |= oneof;
01985
01986 byte construction_counter = 0;
01987 byte construction_stage = 0;
01988
01989 if (_generating_world) {
01990 uint32 r = Random();
01991
01992 construction_stage = TOWN_HOUSE_COMPLETED;
01993 if (Chance16(1, 7)) construction_stage = GB(r, 0, 2);
01994
01995 if (construction_stage == TOWN_HOUSE_COMPLETED) {
01996 ChangePopulation(t, hs->population);
01997 } else {
01998 construction_counter = GB(r, 2, 2);
01999 }
02000 }
02001
02002 MakeTownHouse(tile, t, construction_counter, construction_stage, house, Random());
02003
02004 return true;
02005 }
02006
02007 return false;
02008 }
02009
02016 static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
02017 {
02018 assert(IsTileType(tile, MP_HOUSE));
02019 DecreaseBuildingCount(t, house);
02020 DoClearSquare(tile);
02021 DeleteAnimatedTile(tile);
02022 }
02023
02031 TileIndexDiff GetHouseNorthPart(HouseID &house)
02032 {
02033 if (house >= 3) {
02034 if (GetHouseSpecs(house - 1)->building_flags & TILE_SIZE_2x1) {
02035 house--;
02036 return TileDiffXY(-1, 0);
02037 } else if (GetHouseSpecs(house - 1)->building_flags & BUILDING_2_TILES_Y) {
02038 house--;
02039 return TileDiffXY(0, -1);
02040 } else if (GetHouseSpecs(house - 2)->building_flags & BUILDING_HAS_4_TILES) {
02041 house -= 2;
02042 return TileDiffXY(-1, 0);
02043 } else if (GetHouseSpecs(house - 3)->building_flags & BUILDING_HAS_4_TILES) {
02044 house -= 3;
02045 return TileDiffXY(-1, -1);
02046 }
02047 }
02048 return 0;
02049 }
02050
02051 void ClearTownHouse(Town *t, TileIndex tile)
02052 {
02053 assert(IsTileType(tile, MP_HOUSE));
02054
02055 HouseID house = GetHouseType(tile);
02056
02057
02058 tile += GetHouseNorthPart(house);
02059
02060 const HouseSpec *hs = GetHouseSpecs(house);
02061
02062
02063 if (IsHouseCompleted(tile)) {
02064 ChangePopulation(t, -hs->population);
02065 }
02066
02067 t->num_houses--;
02068
02069
02070 if (hs->building_flags & BUILDING_IS_CHURCH) {
02071 ClrBit(t->flags12, TOWN_HAS_CHURCH);
02072 } else if (hs->building_flags & BUILDING_IS_STADIUM) {
02073 ClrBit(t->flags12, TOWN_HAS_STADIUM);
02074 }
02075
02076
02077 uint eflags = hs->building_flags;
02078 DoClearTownHouseHelper(tile, t, house);
02079 if (eflags & BUILDING_2_TILES_Y) DoClearTownHouseHelper(tile + TileDiffXY(0, 1), t, ++house);
02080 if (eflags & BUILDING_2_TILES_X) DoClearTownHouseHelper(tile + TileDiffXY(1, 0), t, ++house);
02081 if (eflags & BUILDING_HAS_4_TILES) DoClearTownHouseHelper(tile + TileDiffXY(1, 1), t, ++house);
02082 }
02083
02084 static bool IsUniqueTownName(const char *name)
02085 {
02086 const Town *t;
02087
02088 FOR_ALL_TOWNS(t) {
02089 if (t->name != NULL && strcmp(t->name, name) == 0) return false;
02090 }
02091
02092 return true;
02093 }
02094
02101 CommandCost CmdRenameTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02102 {
02103 if (!IsValidTownID(p1)) return CMD_ERROR;
02104
02105 bool reset = StrEmpty(text);
02106
02107 if (!reset) {
02108 if (strlen(text) >= MAX_LENGTH_TOWN_NAME_BYTES) return CMD_ERROR;
02109 if (!IsUniqueTownName(text)) return_cmd_error(STR_NAME_MUST_BE_UNIQUE);
02110 }
02111
02112 if (flags & DC_EXEC) {
02113 Town *t = GetTown(p1);
02114
02115 free(t->name);
02116 t->name = reset ? NULL : strdup(text);
02117
02118 UpdateTownVirtCoord(t);
02119 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
02120 UpdateAllStationVirtCoord();
02121 UpdateAllWaypointSigns();
02122 MarkWholeScreenDirty();
02123 }
02124 return CommandCost();
02125 }
02126
02128 void ExpandTown(Town *t)
02129 {
02130 _generating_world = true;
02131
02132
02133 uint amount = RandomRange(ClampToU16(t->num_houses / 10)) + 3;
02134 t->num_houses += amount;
02135 UpdateTownRadius(t);
02136
02137 uint n = amount * 10;
02138 do GrowTown(t); while (--n);
02139
02140 t->num_houses -= amount;
02141 UpdateTownRadius(t);
02142
02143 UpdateTownMaxPass(t);
02144 _generating_world = false;
02145 }
02146
02147 extern const byte _town_action_costs[8] = {
02148 2, 4, 9, 35, 48, 53, 117, 175
02149 };
02150
02151 static void TownActionAdvertiseSmall(Town *t)
02152 {
02153 ModifyStationRatingAround(t->xy, _current_company, 0x40, 10);
02154 }
02155
02156 static void TownActionAdvertiseMedium(Town *t)
02157 {
02158 ModifyStationRatingAround(t->xy, _current_company, 0x70, 15);
02159 }
02160
02161 static void TownActionAdvertiseLarge(Town *t)
02162 {
02163 ModifyStationRatingAround(t->xy, _current_company, 0xA0, 20);
02164 }
02165
02166 static void TownActionRoadRebuild(Town *t)
02167 {
02168 t->road_build_months = 6;
02169
02170 char *company_name = MallocT<char>(64);
02171 SetDParam(0, _current_company);
02172 GetString(company_name, STR_COMPANY_NAME, company_name + 64);
02173
02174 SetDParam(0, t->index);
02175 SetDParamStr(1, company_name);
02176
02177 AddNewsItem(STR_2055_TRAFFIC_CHAOS_IN_ROAD_REBUILDING,
02178 NS_GENERAL, t->xy, 0, company_name);
02179 }
02180
02181 static bool DoBuildStatueOfCompany(TileIndex tile, TownID town_id)
02182 {
02183
02184 if (IsSteepSlope(GetTileSlope(tile, NULL))) return false;
02185
02186 if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return false;
02187
02188 if (!IsTileType(tile, MP_HOUSE) &&
02189 !IsTileType(tile, MP_CLEAR) &&
02190 !IsTileType(tile, MP_TREES)) {
02191 return false;
02192 }
02193
02194 CompanyID old = _current_company;
02195 _current_company = OWNER_NONE;
02196 CommandCost r = DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
02197 _current_company = old;
02198
02199 if (CmdFailed(r)) return false;
02200
02201 MakeStatue(tile, _current_company, town_id);
02202 MarkTileDirtyByTile(tile);
02203
02204 return true;
02205 }
02206
02213 static bool SearchTileForStatue(TileIndex tile, void *user_data)
02214 {
02215 TownID *town_id = (TownID *)user_data;
02216 return DoBuildStatueOfCompany(tile, *town_id);
02217 }
02218
02224 static void TownActionBuildStatue(Town *t)
02225 {
02226 TileIndex tile = t->xy;
02227
02228 if (CircularTileSearch(&tile, 9, SearchTileForStatue, &t->index)) {
02229 SetBit(t->statues, _current_company);
02230 }
02231 }
02232
02233 static void TownActionFundBuildings(Town *t)
02234 {
02235
02236 t->grow_counter = 1;
02237
02238 SetBit(t->flags12, TOWN_IS_FUNDED);
02239
02240 t->fund_buildings_months = 3;
02241 }
02242
02243 static void TownActionBuyRights(Town *t)
02244 {
02245
02246 if (!_settings_game.economy.exclusive_rights) return;
02247
02248 t->exclusive_counter = 12;
02249 t->exclusivity = _current_company;
02250
02251 ModifyStationRatingAround(t->xy, _current_company, 130, 17);
02252 }
02253
02254 static void TownActionBribe(Town *t)
02255 {
02256 if (Chance16(1, 14)) {
02257
02258 t->unwanted[_current_company] = 6;
02259
02260
02261 Station *st;
02262 FOR_ALL_STATIONS(st) {
02263 if (st->town == t && st->owner == _current_company) {
02264 for (CargoID i = 0; i < NUM_CARGO; i++) st->goods[i].rating = 0;
02265 }
02266 }
02267
02268
02269
02270 if (IsLocalCompany()) ShowErrorMessage(STR_BRIBE_FAILED_2, STR_BRIBE_FAILED, 0, 0);
02271
02272
02273
02274
02275
02276 if (t->ratings[_current_company] > RATING_BRIBE_DOWN_TO) {
02277 t->ratings[_current_company] = RATING_BRIBE_DOWN_TO;
02278 InvalidateWindow(WC_TOWN_AUTHORITY, t->index);
02279 }
02280 } else {
02281 ChangeTownRating(t, RATING_BRIBE_UP_STEP, RATING_BRIBE_MAXIMUM, DC_EXEC);
02282 }
02283 }
02284
02285 typedef void TownActionProc(Town *t);
02286 static TownActionProc *const _town_action_proc[] = {
02287 TownActionAdvertiseSmall,
02288 TownActionAdvertiseMedium,
02289 TownActionAdvertiseLarge,
02290 TownActionRoadRebuild,
02291 TownActionBuildStatue,
02292 TownActionFundBuildings,
02293 TownActionBuyRights,
02294 TownActionBribe
02295 };
02296
02297 enum TownActions {
02298 TACT_NONE = 0x00,
02299
02300 TACT_ADVERTISE_SMALL = 0x01,
02301 TACT_ADVERTISE_MEDIUM = 0x02,
02302 TACT_ADVERTISE_LARGE = 0x04,
02303 TACT_ROAD_REBUILD = 0x08,
02304 TACT_BUILD_STATUE = 0x10,
02305 TACT_FOUND_BUILDINGS = 0x20,
02306 TACT_BUY_RIGHTS = 0x40,
02307 TACT_BRIBE = 0x80,
02308
02309 TACT_ADVERTISE = TACT_ADVERTISE_SMALL | TACT_ADVERTISE_MEDIUM | TACT_ADVERTISE_LARGE,
02310 TACT_CONSTRUCTION = TACT_ROAD_REBUILD | TACT_BUILD_STATUE | TACT_FOUND_BUILDINGS,
02311 TACT_FUNDS = TACT_BUY_RIGHTS | TACT_BRIBE,
02312 TACT_ALL = TACT_ADVERTISE | TACT_CONSTRUCTION | TACT_FUNDS,
02313 };
02314
02315 DECLARE_ENUM_AS_BIT_SET(TownActions);
02316
02323 uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t)
02324 {
02325 int num = 0;
02326 TownActions buttons = TACT_NONE;
02327
02328
02329 if (cid != COMPANY_SPECTATOR && !(_settings_game.economy.bribe && t->unwanted[cid])) {
02330
02331
02332 Money avail = GetCompany(cid)->money + _price.station_value * 200;
02333 Money ref = _price.build_industry >> 8;
02334
02335
02336
02337 for (uint i = 0; i != lengthof(_town_action_costs); i++) {
02338 const TownActions cur = (TownActions)(1 << i);
02339
02340
02341 if (cur == TACT_BRIBE && (!_settings_game.economy.bribe || t->ratings[cid] >= RATING_BRIBE_MAXIMUM))
02342 continue;
02343
02344
02345 if (cur == TACT_BUY_RIGHTS && !_settings_game.economy.exclusive_rights)
02346 continue;
02347
02348
02349 if (cur == TACT_BUILD_STATUE && HasBit(t->statues, cid))
02350 continue;
02351
02352 if (avail >= _town_action_costs[i] * ref) {
02353 buttons |= cur;
02354 num++;
02355 }
02356 }
02357 }
02358
02359 if (nump != NULL) *nump = num;
02360 return buttons;
02361 }
02362
02371 CommandCost CmdDoTownAction(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02372 {
02373 if (!IsValidTownID(p1) || p2 > lengthof(_town_action_proc)) return CMD_ERROR;
02374
02375 Town *t = GetTown(p1);
02376
02377 if (!HasBit(GetMaskOfTownActions(NULL, _current_company, t), p2)) return CMD_ERROR;
02378
02379 CommandCost cost(EXPENSES_OTHER, (_price.build_industry >> 8) * _town_action_costs[p2]);
02380
02381 if (flags & DC_EXEC) {
02382 _town_action_proc[p2](t);
02383 InvalidateWindow(WC_TOWN_AUTHORITY, p1);
02384 }
02385
02386 return cost;
02387 }
02388
02389 static void UpdateTownGrowRate(Town *t)
02390 {
02391
02392 const Company *c;
02393 FOR_ALL_COMPANIES(c) {
02394 if (t->ratings[c->index] < RATING_GROWTH_MAXIMUM) {
02395 t->ratings[c->index] = min((int)RATING_GROWTH_MAXIMUM, t->ratings[c->index] + RATING_GROWTH_UP_STEP);
02396 }
02397 }
02398
02399 int n = 0;
02400
02401 const Station *st;
02402 FOR_ALL_STATIONS(st) {
02403 if (DistanceSquare(st->xy, t->xy) <= t->squared_town_zone_radius[0]) {
02404 if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
02405 n++;
02406 if (IsValidCompanyID(st->owner)) {
02407 int new_rating = t->ratings[st->owner] + RATING_STATION_UP_STEP;
02408 t->ratings[st->owner] = min(new_rating, INT16_MAX);
02409 }
02410 } else {
02411 if (IsValidCompanyID(st->owner)) {
02412 int new_rating = t->ratings[st->owner] + RATING_STATION_DOWN_STEP;
02413 t->ratings[st->owner] = max(new_rating, INT16_MIN);
02414 }
02415 }
02416 }
02417 }
02418
02419
02420 for (uint i = 0; i < MAX_COMPANIES; i++) {
02421 t->ratings[i] = Clamp(t->ratings[i], RATING_MINIMUM, RATING_MAXIMUM);
02422 }
02423
02424 InvalidateWindow(WC_TOWN_AUTHORITY, t->index);
02425
02426 ClrBit(t->flags12, TOWN_IS_FUNDED);
02427 if (_settings_game.economy.town_growth_rate == 0 && t->fund_buildings_months == 0) return;
02428
02431 static const uint16 _grow_count_values[2][6] = {
02432 { 120, 120, 120, 100, 80, 60 },
02433 { 320, 420, 300, 220, 160, 100 }
02434 };
02435
02436 uint16 m;
02437
02438 if (t->fund_buildings_months != 0) {
02439 m = _grow_count_values[0][min(n, 5)];
02440 t->fund_buildings_months--;
02441 } else {
02442 m = _grow_count_values[1][min(n, 5)];
02443 if (n == 0 && !Chance16(1, 12)) return;
02444 }
02445
02446 if (_settings_game.game_creation.landscape == LT_ARCTIC) {
02447 if (TilePixelHeight(t->xy) >= GetSnowLine() && t->act_food == 0 && t->population > 90)
02448 return;
02449 } else if (_settings_game.game_creation.landscape == LT_TROPIC) {
02450 if (GetTropicZone(t->xy) == TROPICZONE_DESERT && (t->act_food == 0 || t->act_water == 0) && t->population > 60)
02451 return;
02452 }
02453
02454
02455
02456 uint growth_multiplier = _settings_game.economy.town_growth_rate != 0 ? _settings_game.economy.town_growth_rate - 1 : 1;
02457
02458 m >>= growth_multiplier;
02459 if (t->larger_town) m /= 2;
02460
02461 t->growth_rate = m / (t->num_houses / 50 + 1);
02462 if (m <= t->grow_counter)
02463 t->grow_counter = m;
02464
02465 SetBit(t->flags12, TOWN_IS_FUNDED);
02466 }
02467
02468 static void UpdateTownAmounts(Town *t)
02469 {
02470
02471 t->pct_pass_transported = t->new_act_pass * 256 / (t->new_max_pass + 1);
02472
02473 t->max_pass = t->new_max_pass; t->new_max_pass = 0;
02474 t->act_pass = t->new_act_pass; t->new_act_pass = 0;
02475 t->act_food = t->new_act_food; t->new_act_food = 0;
02476 t->act_water = t->new_act_water; t->new_act_water = 0;
02477
02478
02479 t->pct_mail_transported = t->new_act_mail * 256 / (t->new_max_mail + 1);
02480 t->max_mail = t->new_max_mail; t->new_max_mail = 0;
02481 t->act_mail = t->new_act_mail; t->new_act_mail = 0;
02482
02483 InvalidateWindow(WC_TOWN_VIEW, t->index);
02484 }
02485
02486 static void UpdateTownUnwanted(Town *t)
02487 {
02488 const Company *c;
02489
02490 FOR_ALL_COMPANIES(c) {
02491 if (t->unwanted[c->index] > 0) t->unwanted[c->index]--;
02492 }
02493 }
02494
02500 bool CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags)
02501 {
02502 if (!IsValidCompanyID(_current_company) || (flags & DC_NO_TEST_TOWN_RATING)) return true;
02503
02504 Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
02505 if (t == NULL) return true;
02506
02507 if (t->ratings[_current_company] > RATING_VERYPOOR) return true;
02508
02509 _error_message = STR_2009_LOCAL_AUTHORITY_REFUSES;
02510 SetDParam(0, t->index);
02511
02512 return false;
02513 }
02514
02515
02516 Town *CalcClosestTownFromTile(TileIndex tile, uint threshold)
02517 {
02518 Town *t;
02519 uint best = threshold;
02520 Town *best_town = NULL;
02521
02522 FOR_ALL_TOWNS(t) {
02523 uint dist = DistanceManhattan(tile, t->xy);
02524 if (dist < best) {
02525 best = dist;
02526 best_town = t;
02527 }
02528 }
02529
02530 return best_town;
02531 }
02532
02533
02534 Town *ClosestTownFromTile(TileIndex tile, uint threshold)
02535 {
02536 switch (GetTileType(tile)) {
02537 case MP_ROAD:
02538 if (!HasTownOwnedRoad(tile)) {
02539 TownID tid = GetTownIndex(tile);
02540 if (tid == (TownID)INVALID_TOWN) {
02541
02542 if (_generating_world) return CalcClosestTownFromTile(tile, threshold);
02543 assert(GetNumTowns() == 0);
02544 return NULL;
02545 }
02546
02547 Town *town = GetTown(tid);
02548 assert(town->IsValid());
02549 assert(town == CalcClosestTownFromTile(tile, UINT_MAX));
02550
02551 if (DistanceManhattan(tile, town->xy) >= threshold) town = NULL;
02552
02553 return town;
02554 }
02555
02556
02557 case MP_HOUSE:
02558 return GetTownByTile(tile);
02559
02560 default:
02561 return CalcClosestTownFromTile(tile, threshold);
02562 }
02563 }
02564
02565 static bool _town_rating_test = false;
02566 SmallMap<const Town *, int, 4> _town_test_ratings;
02567
02568 void SetTownRatingTestMode(bool mode)
02569 {
02570 static int ref_count = 0;
02571 if (mode) {
02572 if (ref_count == 0) {
02573 _town_test_ratings.Clear();
02574 }
02575 ref_count++;
02576 } else {
02577 assert(ref_count > 0);
02578 ref_count--;
02579 }
02580 _town_rating_test = !(ref_count == 0);
02581 }
02582
02583 static int GetRating(const Town *t)
02584 {
02585 if (_town_rating_test) {
02586 SmallMap<const Town *, int>::iterator it = _town_test_ratings.Find(t);
02587 if (it != _town_test_ratings.End()) {
02588 return it->second;
02589 }
02590 }
02591 return t->ratings[_current_company];
02592 }
02593
02601 void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
02602 {
02603
02604 if (t == NULL || (flags & DC_NO_MODIFY_TOWN_RATING) ||
02605 !IsValidCompanyID(_current_company) ||
02606 (_cheats.magic_bulldozer.value && add < 0)) {
02607 return;
02608 }
02609
02610 SetBit(t->have_ratings, _current_company);
02611
02612 int rating = GetRating(t);
02613 if (add < 0) {
02614 if (rating > max) {
02615 rating += add;
02616 if (rating < max) rating = max;
02617 }
02618 } else {
02619 if (rating < max) {
02620 rating += add;
02621 if (rating > max) rating = max;
02622 }
02623 }
02624 if (_town_rating_test) {
02625 _town_test_ratings[t] = rating;
02626 } else {
02627 t->ratings[_current_company] = rating;
02628 InvalidateWindow(WC_TOWN_AUTHORITY, t->index);
02629 }
02630 }
02631
02632
02633 static const int _default_rating_settings [3][3] = {
02634
02635 { 0, 128, 384},
02636 { 48, 192, 480},
02637 { 96, 384, 768},
02638 };
02639
02640 bool CheckforTownRating(DoCommandFlag flags, Town *t, byte type)
02641 {
02642
02643 if (t == NULL || !IsValidCompanyID(_current_company) || _cheats.magic_bulldozer.value)
02644 return true;
02645
02646
02647
02648
02649
02650 int modemod = _default_rating_settings[_settings_game.difficulty.town_council_tolerance][type];
02651
02652 if (GetRating(t) < 16 + modemod && !(flags & DC_NO_TEST_TOWN_RATING)) {
02653 SetDParam(0, t->index);
02654 _error_message = STR_2009_LOCAL_AUTHORITY_REFUSES;
02655 return false;
02656 }
02657
02658 return true;
02659 }
02660
02661 void TownsMonthlyLoop()
02662 {
02663 Town *t;
02664
02665 FOR_ALL_TOWNS(t) {
02666 if (t->road_build_months != 0) t->road_build_months--;
02667
02668 if (t->exclusive_counter != 0)
02669 if (--t->exclusive_counter == 0) t->exclusivity = INVALID_COMPANY;
02670
02671 UpdateTownGrowRate(t);
02672 UpdateTownAmounts(t);
02673 UpdateTownUnwanted(t);
02674 }
02675 }
02676
02677 void TownsYearlyLoop()
02678 {
02679
02680 for (TileIndex t = 0; t < MapSize(); t++) {
02681 if (!IsTileType(t, MP_HOUSE)) continue;
02682 IncrementHouseAge(t);
02683 }
02684 }
02685
02686 void InitializeTowns()
02687 {
02688
02689 _Town_pool.CleanPool();
02690 _Town_pool.AddBlockToPool();
02691
02692 memset(_subsidies, 0, sizeof(_subsidies));
02693 for (Subsidy *s = _subsidies; s != endof(_subsidies); s++) {
02694 s->cargo_type = CT_INVALID;
02695 }
02696
02697 _cur_town_ctr = 0;
02698 _cur_town_iter = 0;
02699 _total_towns = 0;
02700 }
02701
02702 static CommandCost TerraformTile_Town(TileIndex tile, DoCommandFlag flags, uint z_new, Slope tileh_new)
02703 {
02704 if (AutoslopeEnabled()) {
02705 HouseID house = GetHouseType(tile);
02706 GetHouseNorthPart(house);
02707 const HouseSpec *hs = GetHouseSpecs(house);
02708
02709
02710 if (((hs->building_flags & TILE_NOT_SLOPED) == 0) && !IsSteepSlope(tileh_new) &&
02711 (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) return CommandCost(EXPENSES_CONSTRUCTION, _price.terraform);
02712 }
02713
02714 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02715 }
02716
02718 extern const TileTypeProcs _tile_type_town_procs = {
02719 DrawTile_Town,
02720 GetSlopeZ_Town,
02721 ClearTile_Town,
02722 GetAcceptedCargo_Town,
02723 GetTileDesc_Town,
02724 GetTileTrackStatus_Town,
02725 ClickTile_Town,
02726 AnimateTile_Town,
02727 TileLoop_Town,
02728 ChangeTileOwner_Town,
02729 GetProducedCargo_Town,
02730 NULL,
02731 GetFoundation_Town,
02732 TerraformTile_Town,
02733 };
02734
02735 void ResetHouses()
02736 {
02737 memset(&_house_specs, 0, sizeof(_house_specs));
02738 memcpy(&_house_specs, &_original_house_specs, sizeof(_original_house_specs));
02739
02740
02741 _house_mngr.ResetOverride();
02742 }