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 uint32 _cur_town_ctr;
00056 uint32 _cur_town_iter;
00057
00058
00059 DEFINE_OLD_POOL_GENERIC(Town, Town)
00060
00061 Town::Town(TileIndex tile)
00062 {
00063 if (tile != INVALID_TILE) _total_towns++;
00064 this->xy = tile;
00065 }
00066
00067 Town::~Town()
00068 {
00069 free(this->name);
00070
00071 if (CleaningPool()) return;
00072
00073 Industry *i;
00074
00075
00076
00077 DeleteWindowById(WC_TOWN_VIEW, this->index);
00078 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
00079 _total_towns--;
00080
00081
00082 FOR_ALL_INDUSTRIES(i) if (i->town == this) delete i;
00083
00084
00085 for (TileIndex tile = 0; tile < MapSize(); ++tile) {
00086 switch (GetTileType(tile)) {
00087 case MP_HOUSE:
00088 if (GetTownByTile(tile) == this) DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
00089 break;
00090
00091 case MP_ROAD:
00092
00093 if (HasTownOwnedRoad(tile) && GetTownIndex(tile) == this->index) {
00094 DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
00095 }
00096 break;
00097
00098 case MP_TUNNELBRIDGE:
00099 if (IsTileOwner(tile, OWNER_TOWN) &&
00100 ClosestTownFromTile(tile, UINT_MAX) == this)
00101 DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
00102 break;
00103
00104 default:
00105 break;
00106 }
00107 }
00108
00109 DeleteSubsidyWithTown(this->index);
00110
00111 MarkWholeScreenDirty();
00112
00113 this->xy = INVALID_TILE;
00114
00115 UpdateNearestTownForRoadTiles(false);
00116 }
00117
00121 void Town::InitializeLayout(TownLayout layout)
00122 {
00123 if (layout != TL_RANDOM) {
00124 this->layout = layout;
00125 return;
00126 }
00127
00128 this->layout = TileHash(TileX(this->xy), TileY(this->xy)) % (NUM_TLS - 1);
00129 }
00130
00131 Money HouseSpec::GetRemovalCost() const
00132 {
00133 return (_price.remove_house * this->removal_cost) >> 8;
00134 }
00135
00136
00137 static int _grow_town_result;
00138
00139
00140 enum TownGrowthResult {
00141 GROWTH_SUCCEED = -1,
00142 GROWTH_SEARCH_STOPPED = 0
00143
00144 };
00145
00146 static bool BuildTownHouse(Town *t, TileIndex tile);
00147
00148 static void TownDrawHouseLift(const TileInfo *ti)
00149 {
00150 AddChildSpriteScreen(SPR_LIFT, PAL_NONE, 14, 60 - GetLiftPosition(ti->tile));
00151 }
00152
00153 typedef void TownDrawTileProc(const TileInfo *ti);
00154 static TownDrawTileProc * const _town_draw_tile_procs[1] = {
00155 TownDrawHouseLift
00156 };
00157
00163 static inline DiagDirection RandomDiagDir()
00164 {
00165 return (DiagDirection)(3 & Random());
00166 }
00167
00173 static void DrawTile_Town(TileInfo *ti)
00174 {
00175 HouseID house_id = GetHouseType(ti->tile);
00176
00177 if (house_id >= NEW_HOUSE_OFFSET) {
00178
00179
00180
00181 if (GetHouseSpecs(house_id)->spritegroup != NULL) {
00182 DrawNewHouseTile(ti, house_id);
00183 return;
00184 } else {
00185 house_id = GetHouseSpecs(house_id)->substitute_id;
00186 }
00187 }
00188
00189
00190 const DrawBuildingsTileStruct *dcts = &_town_draw_tile_data[house_id << 4 | TileHash2Bit(ti->x, ti->y) << 2 | GetHouseBuildingStage(ti->tile)];
00191
00192 if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
00193
00194 DrawGroundSprite(dcts->ground.sprite, dcts->ground.pal);
00195
00196
00197 if (IsInvisibilitySet(TO_HOUSES)) return;
00198
00199
00200 SpriteID image = dcts->building.sprite;
00201 if (image != 0) {
00202 AddSortableSpriteToDraw(image, dcts->building.pal,
00203 ti->x + dcts->subtile_x,
00204 ti->y + dcts->subtile_y,
00205 dcts->width,
00206 dcts->height,
00207 dcts->dz,
00208 ti->z,
00209 IsTransparencySet(TO_HOUSES)
00210 );
00211
00212 if (IsTransparencySet(TO_HOUSES)) return;
00213 }
00214
00215 {
00216 int proc = dcts->draw_proc - 1;
00217
00218 if (proc >= 0) _town_draw_tile_procs[proc](ti);
00219 }
00220 }
00221
00222 static uint GetSlopeZ_Town(TileIndex tile, uint x, uint y)
00223 {
00224 return GetTileMaxZ(tile);
00225 }
00226
00228 static Foundation GetFoundation_Town(TileIndex tile, Slope tileh)
00229 {
00230 return FlatteningFoundation(tileh);
00231 }
00232
00239 static void AnimateTile_Town(TileIndex tile)
00240 {
00241 if (GetHouseType(tile) >= NEW_HOUSE_OFFSET) {
00242 AnimateNewHouseTile(tile);
00243 return;
00244 }
00245
00246 if (_tick_counter & 3) return;
00247
00248
00249
00250
00251
00252 if (!(GetHouseSpecs(GetHouseType(tile))->building_flags & BUILDING_IS_ANIMATED)) {
00253 DeleteAnimatedTile(tile);
00254 return;
00255 }
00256
00257 if (!LiftHasDestination(tile)) {
00258 uint i;
00259
00260
00261
00262
00263
00264 do {
00265 i = RandomRange(7);
00266 } while (i == 1 || i * 6 == GetLiftPosition(tile));
00267
00268 SetLiftDestination(tile, i);
00269 }
00270
00271 int pos = GetLiftPosition(tile);
00272 int dest = GetLiftDestination(tile) * 6;
00273 pos += (pos < dest) ? 1 : -1;
00274 SetLiftPosition(tile, pos);
00275
00276 if (pos == dest) {
00277 HaltLift(tile);
00278 DeleteAnimatedTile(tile);
00279 }
00280
00281 MarkTileDirtyByTile(tile);
00282 }
00283
00290 static bool IsCloseToTown(TileIndex tile, uint dist)
00291 {
00292 const Town *t;
00293
00294 FOR_ALL_TOWNS(t) {
00295 if (DistanceManhattan(tile, t->xy) < dist) return true;
00296 }
00297 return false;
00298 }
00299
00308 static void MarkTownSignDirty(Town *t)
00309 {
00310 MarkAllViewportsDirty(
00311 t->sign.left - 6,
00312 t->sign.top - 3,
00313 t->sign.left + t->sign.width_1 * 4 + 12,
00314 t->sign.top + 45
00315 );
00316 }
00317
00323 void UpdateTownVirtCoord(Town *t)
00324 {
00325 MarkTownSignDirty(t);
00326 Point pt = RemapCoords2(TileX(t->xy) * TILE_SIZE, TileY(t->xy) * TILE_SIZE);
00327 SetDParam(0, t->index);
00328 SetDParam(1, t->population);
00329 UpdateViewportSignPos(&t->sign, pt.x, pt.y - 24,
00330 _settings_client.gui.population_in_label ? STR_TOWN_LABEL_POP : STR_TOWN_LABEL);
00331 MarkTownSignDirty(t);
00332 }
00333
00335 void UpdateAllTownVirtCoords()
00336 {
00337 Town *t;
00338 FOR_ALL_TOWNS(t) {
00339 UpdateTownVirtCoord(t);
00340 }
00341 }
00342
00348 static void ChangePopulation(Town *t, int mod)
00349 {
00350 t->population += mod;
00351 InvalidateWindow(WC_TOWN_VIEW, t->index);
00352 UpdateTownVirtCoord(t);
00353
00354 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
00355 }
00356
00362 uint32 GetWorldPopulation()
00363 {
00364 uint32 pop = 0;
00365 const Town *t;
00366
00367 FOR_ALL_TOWNS(t) pop += t->population;
00368 return pop;
00369 }
00370
00375 static void MakeSingleHouseBigger(TileIndex tile)
00376 {
00377 assert(IsTileType(tile, MP_HOUSE));
00378
00379
00380 if (LiftHasDestination(tile)) return;
00381
00382
00383 IncHouseConstructionTick(tile);
00384 if (GetHouseConstructionTick(tile) != 0) return;
00385
00386 const HouseSpec *hs = GetHouseSpecs(GetHouseType(tile));
00387
00388
00389 if (HasBit(hs->callback_mask, CBM_HOUSE_CONSTRUCTION_STATE_CHANGE)) {
00390 uint16 callback_res = GetHouseCallback(CBID_HOUSE_CONSTRUCTION_STATE_CHANGE, 0, 0, GetHouseType(tile), GetTownByTile(tile), tile);
00391 if (callback_res != CALLBACK_FAILED) ChangeHouseAnimationFrame(hs->grffile, tile, callback_res);
00392 }
00393
00394 if (IsHouseCompleted(tile)) {
00395
00396
00397 ChangePopulation(GetTownByTile(tile), hs->population);
00398 ResetHouseAge(tile);
00399 }
00400 MarkTileDirtyByTile(tile);
00401 }
00402
00406 static void MakeTownHouseBigger(TileIndex tile)
00407 {
00408 uint flags = GetHouseSpecs(GetHouseType(tile))->building_flags;
00409 if (flags & BUILDING_HAS_1_TILE) MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 0));
00410 if (flags & BUILDING_2_TILES_Y) MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 1));
00411 if (flags & BUILDING_2_TILES_X) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 0));
00412 if (flags & BUILDING_HAS_4_TILES) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 1));
00413 }
00414
00421 static void TileLoop_Town(TileIndex tile)
00422 {
00423 HouseID house_id = GetHouseType(tile);
00424
00425
00426
00427 if (house_id >= NEW_HOUSE_OFFSET && !NewHouseTileLoop(tile)) return;
00428
00429 if (!IsHouseCompleted(tile)) {
00430
00431 MakeTownHouseBigger(tile);
00432 return;
00433 }
00434
00435 const HouseSpec *hs = GetHouseSpecs(house_id);
00436
00437
00438 if ((hs->building_flags & BUILDING_IS_ANIMATED) &&
00439 house_id < NEW_HOUSE_OFFSET &&
00440 !LiftHasDestination(tile) &&
00441 Chance16(1, 2)) {
00442 AddAnimatedTile(tile);
00443 }
00444
00445 Town *t = GetTownByTile(tile);
00446 uint32 r = Random();
00447
00448 if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
00449 for (uint i = 0; i < 256; i++) {
00450 uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, r, house_id, t, tile);
00451
00452 if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
00453
00454 CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grffile);
00455 if (cargo == CT_INVALID) continue;
00456
00457 uint amt = GB(callback, 0, 8);
00458 if (amt == 0) continue;
00459
00460 uint moved = MoveGoodsToStation(tile, 1, 1, cargo, amt);
00461
00462 const CargoSpec *cs = GetCargo(cargo);
00463 switch (cs->town_effect) {
00464 case TE_PASSENGERS:
00465 t->new_max_pass += amt;
00466 t->new_act_pass += moved;
00467 break;
00468
00469 case TE_MAIL:
00470 t->new_max_mail += amt;
00471 t->new_act_mail += moved;
00472 break;
00473
00474 default:
00475 break;
00476 }
00477 }
00478 } else {
00479 if (GB(r, 0, 8) < hs->population) {
00480 uint amt = GB(r, 0, 8) / 8 + 1;
00481
00482 if (_economy.fluct <= 0) amt = (amt + 1) >> 1;
00483 t->new_max_pass += amt;
00484 t->new_act_pass += MoveGoodsToStation(tile, 1, 1, CT_PASSENGERS, amt);
00485 }
00486
00487 if (GB(r, 8, 8) < hs->mail_generation) {
00488 uint amt = GB(r, 8, 8) / 8 + 1;
00489
00490 if (_economy.fluct <= 0) amt = (amt + 1) >> 1;
00491 t->new_max_mail += amt;
00492 t->new_act_mail += MoveGoodsToStation(tile, 1, 1, CT_MAIL, amt);
00493 }
00494 }
00495
00496 _current_company = OWNER_TOWN;
00497
00498 if (hs->building_flags & BUILDING_HAS_1_TILE &&
00499 HasBit(t->flags12, TOWN_IS_FUNDED) &&
00500 CanDeleteHouse(tile) &&
00501 GetHouseAge(tile) >= hs->minimum_life &&
00502 --t->time_until_rebuild == 0) {
00503 t->time_until_rebuild = GB(r, 16, 8) + 192;
00504
00505 ClearTownHouse(t, tile);
00506
00507
00508 if (GB(r, 24, 8) >= 12) BuildTownHouse(t, tile);
00509 }
00510
00511 _current_company = OWNER_NONE;
00512 }
00513
00518 static bool ClickTile_Town(TileIndex tile)
00519 {
00520
00521 return false;
00522 }
00523
00524 static CommandCost ClearTile_Town(TileIndex tile, DoCommandFlag flags)
00525 {
00526 if (flags & DC_AUTO) return_cmd_error(STR_2004_BUILDING_MUST_BE_DEMOLISHED);
00527 if (!CanDeleteHouse(tile)) return CMD_ERROR;
00528
00529 const HouseSpec *hs = GetHouseSpecs(GetHouseType(tile));
00530
00531 CommandCost cost(EXPENSES_CONSTRUCTION);
00532 cost.AddCost(hs->GetRemovalCost());
00533
00534 int rating = hs->remove_rating_decrease;
00535 _cleared_town_rating += rating;
00536 Town *t = _cleared_town = GetTownByTile(tile);
00537
00538 if (IsValidCompanyID(_current_company)) {
00539 if (rating > t->ratings[_current_company] && !(flags & DC_NO_TEST_TOWN_RATING) && !_cheats.magic_bulldozer.value) {
00540 SetDParam(0, t->index);
00541 return_cmd_error(STR_2009_LOCAL_AUTHORITY_REFUSES);
00542 }
00543 }
00544
00545 ChangeTownRating(t, -rating, RATING_HOUSE_MINIMUM, flags);
00546 if (flags & DC_EXEC) {
00547 ClearTownHouse(t, tile);
00548 }
00549
00550 return cost;
00551 }
00552
00553 static void GetProducedCargo_Town(TileIndex tile, CargoID *b)
00554 {
00555 HouseID house_id = GetHouseType(tile);
00556 const HouseSpec *hs = GetHouseSpecs(house_id);
00557 Town *t = GetTownByTile(tile);
00558
00559 if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
00560 for (uint i = 0; i < 256; i++) {
00561 uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, 0, house_id, t, tile);
00562
00563 if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
00564
00565 CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grffile);
00566
00567 if (cargo == CT_INVALID) continue;
00568 *(b++) = cargo;
00569 }
00570 } else {
00571 if (hs->population > 0) {
00572 *(b++) = CT_PASSENGERS;
00573 }
00574 if (hs->mail_generation > 0) {
00575 *(b++) = CT_MAIL;
00576 }
00577 }
00578 }
00579
00580 static void GetAcceptedCargo_Town(TileIndex tile, AcceptedCargo ac)
00581 {
00582 const HouseSpec *hs = GetHouseSpecs(GetHouseType(tile));
00583 CargoID accepts[3];
00584
00585
00586 for (uint8 i = 0; i < lengthof(accepts); i++) {
00587 accepts[i] = hs->accepts_cargo[i];
00588 }
00589
00590
00591 if (HasBit(hs->callback_mask, CBM_HOUSE_ACCEPT_CARGO)) {
00592 uint16 callback = GetHouseCallback(CBID_HOUSE_ACCEPT_CARGO, 0, 0, GetHouseType(tile), GetTownByTile(tile), tile);
00593 if (callback != CALLBACK_FAILED) {
00594
00595 accepts[0] = GetCargoTranslation(GB(callback, 0, 5), hs->grffile);
00596 accepts[1] = GetCargoTranslation(GB(callback, 5, 5), hs->grffile);
00597 accepts[2] = GetCargoTranslation(GB(callback, 10, 5), hs->grffile);
00598 }
00599 }
00600
00601
00602 if (HasBit(hs->callback_mask, CBM_HOUSE_CARGO_ACCEPTANCE)) {
00603 uint16 callback = GetHouseCallback(CBID_HOUSE_CARGO_ACCEPTANCE, 0, 0, GetHouseType(tile), GetTownByTile(tile), tile);
00604 if (callback != CALLBACK_FAILED) {
00605 if (accepts[0] != CT_INVALID) ac[accepts[0]] = GB(callback, 0, 4);
00606 if (accepts[1] != CT_INVALID) ac[accepts[1]] = GB(callback, 4, 4);
00607 if (_settings_game.game_creation.landscape != LT_TEMPERATE && HasBit(callback, 12)) {
00608
00609 ac[CT_FOOD] = GB(callback, 8, 4);
00610 } else {
00611 if (accepts[2] != CT_INVALID) ac[accepts[2]] = GB(callback, 8, 4);
00612 }
00613 return;
00614 }
00615 }
00616
00617
00618 for (uint8 i = 0; i < lengthof(accepts); i++) {
00619 if (accepts[i] != CT_INVALID) ac[accepts[i]] = hs->cargo_acceptance[i];
00620 }
00621 }
00622
00623 static void GetTileDesc_Town(TileIndex tile, TileDesc *td)
00624 {
00625 const HouseID house = GetHouseType(tile);
00626 const HouseSpec *hs = GetHouseSpecs(house);
00627 bool house_completed = IsHouseCompleted(tile);
00628
00629 td->str = hs->building_name;
00630
00631 uint16 callback_res = GetHouseCallback(CBID_HOUSE_CUSTOM_NAME, house_completed ? 1 : 0, 0, house, GetTownByTile(tile), tile);
00632 if (callback_res != CALLBACK_FAILED) {
00633 StringID new_name = GetGRFStringID(hs->grffile->grfid, 0xD000 + callback_res);
00634 if (new_name != STR_NULL && new_name != STR_UNDEFINED) {
00635 td->str = new_name;
00636 }
00637 }
00638
00639 if (!house_completed) {
00640 SetDParamX(td->dparam, 0, td->str);
00641 td->str = STR_2058_UNDER_CONSTRUCTION;
00642 }
00643
00644 if (hs->grffile != NULL) {
00645 const GRFConfig *gc = GetGRFConfig(hs->grffile->grfid);
00646 td->grf = gc->name;
00647 }
00648
00649 td->owner[0] = OWNER_TOWN;
00650 }
00651
00652 static TrackStatus GetTileTrackStatus_Town(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
00653 {
00654
00655 return 0;
00656 }
00657
00658 static void ChangeTileOwner_Town(TileIndex tile, Owner old_owner, Owner new_owner)
00659 {
00660
00661 }
00662
00663 static bool GrowTown(Town *t);
00664
00665 static void TownTickHandler(Town *t)
00666 {
00667 if (HasBit(t->flags12, TOWN_IS_FUNDED)) {
00668 int i = t->grow_counter - 1;
00669 if (i < 0) {
00670 if (GrowTown(t)) {
00671 i = t->growth_rate;
00672 } else {
00673 i = 0;
00674 }
00675 }
00676 t->grow_counter = i;
00677 }
00678
00679 UpdateTownRadius(t);
00680 }
00681
00682 void OnTick_Town()
00683 {
00684 if (_game_mode == GM_EDITOR) return;
00685
00686 Town *t;
00687 FOR_ALL_TOWNS(t) {
00688
00689 if ((_tick_counter + t->index) % TOWN_GROWTH_FREQUENCY == 0) {
00690 TownTickHandler(t);
00691 }
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 assert(tile < MapSize());
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 assert(tile < MapSize());
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 assert(tile < MapSize());
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 assert(tile < MapSize());
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 extern int _nb_orig_names;
01368
01373 struct TownNameParams {
01374 uint32 grfid;
01375 uint16 townnametype;
01376 bool grf;
01377
01378 TownNameParams(byte town_name)
01379 {
01380 this->grf = town_name >= _nb_orig_names;
01381 this->grfid = this->grf ? GetGRFTownNameId(town_name - _nb_orig_names) : 0;
01382 this->townnametype = this->grf ? GetGRFTownNameType(town_name - _nb_orig_names) : SPECSTR_TOWNNAME_START + town_name;
01383 }
01384 };
01385
01392 static bool VerifyTownName(uint32 r, const TownNameParams *par)
01393 {
01394
01395 char buf1[MAX_LENGTH_TOWN_NAME_BYTES + 4 + 1];
01396 char buf2[MAX_LENGTH_TOWN_NAME_BYTES + 4 + 1];
01397
01398 SetDParam(0, r);
01399 if (par->grf && par->grfid != 0) {
01400 GRFTownNameGenerate(buf1, par->grfid, par->townnametype, r, lastof(buf1));
01401 } else {
01402 GetString(buf1, par->townnametype, lastof(buf1));
01403 }
01404
01405
01406 if (strlen(buf1) >= MAX_LENGTH_TOWN_NAME_BYTES) return false;
01407
01408 const Town *t;
01409 FOR_ALL_TOWNS(t) {
01410
01411
01412 SetDParam(0, t->index);
01413 GetString(buf2, STR_TOWN, lastof(buf2));
01414 if (strcmp(buf1, buf2) == 0) return false;
01415 }
01416
01417 return true;
01418 }
01419
01425 bool GenerateTownName(uint32 *townnameparts)
01426 {
01427
01428
01429
01430
01431
01432 int tries = 1000;
01433 TownNameParams par(_settings_game.game_creation.town_name);
01434
01435 assert(townnameparts != NULL);
01436
01437 for (;;) {
01438 uint32 r = InteractiveRandom();
01439
01440 if (!VerifyTownName(r, &par)) {
01441 if (tries-- < 0) return false;
01442 continue;
01443 }
01444
01445 *townnameparts = r;
01446 return true;
01447 }
01448 }
01449
01450 void UpdateTownMaxPass(Town *t)
01451 {
01452 t->max_pass = t->population >> 3;
01453 t->max_mail = t->population >> 4;
01454 }
01455
01465 static void DoCreateTown(Town *t, TileIndex tile, uint32 townnameparts, TownSize size, bool city, TownLayout layout)
01466 {
01467 t->xy = tile;
01468 t->num_houses = 0;
01469 t->time_until_rebuild = 10;
01470 UpdateTownRadius(t);
01471 t->flags12 = 0;
01472 t->population = 0;
01473 t->grow_counter = 0;
01474 t->growth_rate = 250;
01475 t->new_max_pass = 0;
01476 t->new_max_mail = 0;
01477 t->new_act_pass = 0;
01478 t->new_act_mail = 0;
01479 t->max_pass = 0;
01480 t->max_mail = 0;
01481 t->act_pass = 0;
01482 t->act_mail = 0;
01483
01484 t->pct_pass_transported = 0;
01485 t->pct_mail_transported = 0;
01486 t->fund_buildings_months = 0;
01487 t->new_act_food = 0;
01488 t->new_act_water = 0;
01489 t->act_food = 0;
01490 t->act_water = 0;
01491
01492 for (uint i = 0; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
01493
01494 t->have_ratings = 0;
01495 t->exclusivity = INVALID_COMPANY;
01496 t->exclusive_counter = 0;
01497 t->statues = 0;
01498
01499 if (_settings_game.game_creation.town_name < _nb_orig_names) {
01500
01501 t->townnamegrfid = 0;
01502 t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
01503 } else {
01504
01505 t->townnamegrfid = GetGRFTownNameId(_settings_game.game_creation.town_name - _nb_orig_names);
01506 t->townnametype = GetGRFTownNameType(_settings_game.game_creation.town_name - _nb_orig_names);
01507 }
01508 t->townnameparts = townnameparts;
01509
01510 UpdateTownVirtCoord(t);
01511 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
01512
01513 t->InitializeLayout(layout);
01514
01515 t->larger_town = city;
01516
01517 int x = (int)size * 16 + 3;
01518 if (size == TS_RANDOM) x = (Random() & 0xF) + 8;
01519 if (city) x *= _settings_game.economy.initial_city_size;
01520
01521 t->num_houses += x;
01522 UpdateTownRadius(t);
01523
01524 int i = x * 4;
01525 do {
01526 GrowTown(t);
01527 } while (--i);
01528
01529 t->num_houses -= x;
01530 UpdateTownRadius(t);
01531 UpdateTownMaxPass(t);
01532 UpdateAirportsNoise();
01533 }
01534
01545 CommandCost CmdBuildTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01546 {
01547
01548 if (_game_mode != GM_EDITOR) return CMD_ERROR;
01549
01550 TownSize size = (TownSize)GB(p1, 0, 2);
01551 bool city = HasBit(p1, 2);
01552 TownLayout layout = (TownLayout)GB(p1, 3, 3);
01553 TownNameParams par(_settings_game.game_creation.town_name);
01554 uint32 townnameparts = p2;
01555
01556 if (size > TS_RANDOM) return CMD_ERROR;
01557 if (layout > TL_RANDOM) return CMD_ERROR;
01558 if (!VerifyTownName(townnameparts, &par)) return_cmd_error(STR_NAME_MUST_BE_UNIQUE);
01559
01560
01561 if (DistanceFromEdge(tile) < 12) {
01562 return_cmd_error(STR_0237_TOO_CLOSE_TO_EDGE_OF_MAP);
01563 }
01564
01565
01566 if (IsCloseToTown(tile, 20)) {
01567 return_cmd_error(STR_0238_TOO_CLOSE_TO_ANOTHER_TOWN);
01568 }
01569
01570
01571 if ((!IsTileType(tile, MP_CLEAR) && !IsTileType(tile, MP_TREES)) || GetTileSlope(tile, NULL) != SLOPE_FLAT) {
01572 return_cmd_error(STR_0239_SITE_UNSUITABLE);
01573 }
01574
01575
01576 if (!Town::CanAllocateItem()) return_cmd_error(STR_023A_TOO_MANY_TOWNS);
01577
01578
01579 if (flags & DC_EXEC) {
01580 Town *t = new Town(tile);
01581 _generating_world = true;
01582 UpdateNearestTownForRoadTiles(true);
01583 DoCreateTown(t, tile, townnameparts, size, city, layout);
01584 UpdateNearestTownForRoadTiles(false);
01585 _generating_world = false;
01586 }
01587 return CommandCost();
01588 }
01589
01590 Town *CreateRandomTown(uint attempts, TownSize size, bool city, TownLayout layout)
01591 {
01592 if (!Town::CanAllocateItem()) return NULL;
01593
01594 do {
01595
01596 TileIndex tile = RandomTile();
01597 switch (layout) {
01598 case TL_2X2_GRID:
01599 tile = TileXY(TileX(tile) - TileX(tile) % 3, TileY(tile) - TileY(tile) % 3);
01600 break;
01601 case TL_3X3_GRID:
01602 tile = TileXY(TileX(tile) & ~3, TileY(tile) & ~3);
01603 break;
01604 default: break;
01605 }
01606 if (DistanceFromEdge(tile) < 20) continue;
01607
01608
01609 if (!IsTileType(tile, MP_CLEAR) || GetTileSlope(tile, NULL) != SLOPE_FLAT) continue;
01610
01611
01612 if (IsCloseToTown(tile, 20)) continue;
01613
01614 uint32 townnameparts;
01615
01616
01617 if (!GenerateTownName(&townnameparts)) break;
01618
01619
01620 Town *t = new Town(tile);
01621
01622 DoCreateTown(t, tile, townnameparts, size, city, layout);
01623 return t;
01624 } while (--attempts != 0);
01625
01626 return NULL;
01627 }
01628
01629 static const byte _num_initial_towns[4] = {5, 11, 23, 46};
01630
01631 bool GenerateTowns(TownLayout layout)
01632 {
01633 uint num = 0;
01634 uint difficulty = _settings_game.difficulty.number_towns;
01635 uint n = (difficulty == (uint)CUSTOM_TOWN_NUMBER_DIFFICULTY) ? _settings_game.game_creation.custom_town_number : ScaleByMapSize(_num_initial_towns[difficulty] + (Random() & 7));
01636
01637 SetGeneratingWorldProgress(GWP_TOWN, n);
01638
01639 do {
01640 bool city = (_settings_game.economy.larger_towns != 0 && Chance16(1, _settings_game.economy.larger_towns));
01641 IncreaseGeneratingWorldProgress(GWP_TOWN);
01642
01643 if (CreateRandomTown(20, TS_RANDOM, city, layout) != NULL) num++;
01644 } while (--n);
01645
01646
01647 if (num == 0 && CreateRandomTown(10000, TS_RANDOM, _settings_game.economy.larger_towns != 0, layout) == NULL) {
01648 if (GetNumTowns() == 0) {
01649 if (_game_mode != GM_EDITOR) {
01650 extern StringID _switch_mode_errorstr;
01651 _switch_mode_errorstr = STR_COULD_NOT_CREATE_TOWN;
01652 }
01653
01654 return false;
01655 }
01656 }
01657
01658 return true;
01659 }
01660
01661
01667 HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
01668 {
01669 uint dist = DistanceSquare(tile, t->xy);
01670
01671 if (t->fund_buildings_months && dist <= 25) return HZB_TOWN_CENTRE;
01672
01673 HouseZonesBits smallest = HZB_TOWN_EDGE;
01674 for (HouseZonesBits i = HZB_BEGIN; i < HZB_END; i++) {
01675 if (dist < t->squared_town_zone_radius[i]) smallest = i;
01676 }
01677
01678 return smallest;
01679 }
01680
01691 static inline void ClearMakeHouseTile(TileIndex tile, Town *t, byte counter, byte stage, HouseID type, byte random_bits)
01692 {
01693 CommandCost cc = DoCommand(tile, 0, 0, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR);
01694
01695 assert(CmdSucceeded(cc));
01696
01697 IncreaseBuildingCount(t, type);
01698 MakeHouseTile(tile, t->index, counter, stage, type, random_bits);
01699 if (GetHouseSpecs(type)->building_flags & BUILDING_IS_ANIMATED) AddAnimatedTile(tile);
01700
01701 MarkTileDirtyByTile(tile);
01702 }
01703
01704
01715 static void MakeTownHouse(TileIndex t, Town *town, byte counter, byte stage, HouseID type, byte random_bits)
01716 {
01717 BuildingFlags size = GetHouseSpecs(type)->building_flags;
01718
01719 ClearMakeHouseTile(t, town, counter, stage, type, random_bits);
01720 if (size & BUILDING_2_TILES_Y) ClearMakeHouseTile(t + TileDiffXY(0, 1), town, counter, stage, ++type, random_bits);
01721 if (size & BUILDING_2_TILES_X) ClearMakeHouseTile(t + TileDiffXY(1, 0), town, counter, stage, ++type, random_bits);
01722 if (size & BUILDING_HAS_4_TILES) ClearMakeHouseTile(t + TileDiffXY(1, 1), town, counter, stage, ++type, random_bits);
01723 }
01724
01725
01734 static inline bool CanBuildHouseHere(TileIndex tile, TownID town, bool noslope)
01735 {
01736
01737 Slope slope = GetTileSlope(tile, NULL);
01738 if ((noslope && slope != SLOPE_FLAT) || IsSteepSlope(slope)) return false;
01739
01740
01741 if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return false;
01742
01743
01744 if (IsTileType(tile, MP_HOUSE) && GetTownIndex(tile) != town) return false;
01745
01746
01747 return CmdSucceeded(DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR));
01748 }
01749
01750
01760 static inline bool CheckBuildHouseSameZ(TileIndex tile, TownID town, uint z, bool noslope)
01761 {
01762 if (!CanBuildHouseHere(tile, town, noslope)) return false;
01763
01764
01765 if (GetTileMaxZ(tile) != z) return false;
01766
01767 return true;
01768 }
01769
01770
01780 static bool CheckFree2x2Area(TileIndex tile, TownID town, uint z, bool noslope)
01781 {
01782
01783 if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
01784
01785 for (DiagDirection d = DIAGDIR_SE; d < DIAGDIR_END; d++) {
01786 tile += TileOffsByDiagDir(d);
01787 if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
01788 }
01789
01790 return true;
01791 }
01792
01793
01801 static inline bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile)
01802 {
01803
01804 if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
01805
01806 TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
01807
01808 switch (t->layout) {
01809 case TL_2X2_GRID:
01810 if ((grid_pos.x % 3) == 0 || (grid_pos.y % 3) == 0) return false;
01811 break;
01812
01813 case TL_3X3_GRID:
01814 if ((grid_pos.x % 4) == 0 || (grid_pos.y % 4) == 0) return false;
01815 break;
01816
01817 default:
01818 break;
01819 }
01820
01821 return true;
01822 }
01823
01824
01832 static inline bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile)
01833 {
01834
01835 if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
01836
01837
01838
01839 uint dx = MapSize() + TileX(t->xy) - TileX(tile);
01840 uint dy = MapSize() + TileY(t->xy) - TileY(tile);
01841
01842 switch (t->layout) {
01843 case TL_2X2_GRID:
01844 if ((dx % 3) != 0 || (dy % 3) != 0) return false;
01845 break;
01846
01847 case TL_3X3_GRID:
01848 if ((dx % 4) < 2 || (dy % 4) < 2) return false;
01849 break;
01850
01851 default:
01852 break;
01853 }
01854
01855 return true;
01856 }
01857
01858
01868 static bool CheckTownBuild2House(TileIndex *tile, Town *t, uint maxz, bool noslope, DiagDirection second)
01869 {
01870
01871
01872 TileIndex tile2 = *tile + TileOffsByDiagDir(second);
01873 if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) return true;
01874
01875 tile2 = *tile + TileOffsByDiagDir(ReverseDiagDir(second));
01876 if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) {
01877 *tile = tile2;
01878 return true;
01879 }
01880
01881 return false;
01882 }
01883
01884
01893 static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, uint maxz, bool noslope)
01894 {
01895 TileIndex tile2 = *tile;
01896
01897 for (DiagDirection d = DIAGDIR_SE;;d++) {
01898 if (TownLayoutAllows2x2HouseHere(t, tile2) && CheckFree2x2Area(tile2, t->index, maxz, noslope)) {
01899 *tile = tile2;
01900 return true;
01901 }
01902 if (d == DIAGDIR_END) break;
01903 tile2 += TileOffsByDiagDir(ReverseDiagDir(d));
01904 }
01905
01906 return false;
01907 }
01908
01909
01916 static bool BuildTownHouse(Town *t, TileIndex tile)
01917 {
01918
01919 if (!TownLayoutAllowsHouseHere(t, tile)) return false;
01920
01921
01922 if (!CanBuildHouseHere(tile, t->index, false)) return false;
01923
01924 uint z;
01925 Slope slope = GetTileSlope(tile, &z);
01926
01927
01928
01929 HouseZonesBits rad = GetTownRadiusGroup(t, tile);
01930
01931
01932 int land = _settings_game.game_creation.landscape;
01933 if (land == LT_ARCTIC && z >= _settings_game.game_creation.snow_line) land = -1;
01934
01935 uint bitmask = (1 << rad) + (1 << (land + 12));
01936
01937
01938
01939
01940 HouseID houses[HOUSE_MAX];
01941 uint num = 0;
01942 uint probs[HOUSE_MAX];
01943 uint probability_max = 0;
01944
01945
01946 for (uint i = 0; i < HOUSE_MAX; i++) {
01947 const HouseSpec *hs = GetHouseSpecs(i);
01948
01949
01950 if ((~hs->building_availability & bitmask) != 0 || !hs->enabled) continue;
01951
01952
01953 if (hs->class_id != HOUSE_NO_CLASS) {
01954
01955 if (t->building_counts.class_count[hs->class_id] == UINT16_MAX) continue;
01956 } else {
01957
01958 if (t->building_counts.id_count[i] == UINT16_MAX) continue;
01959 }
01960
01961
01962 uint cur_prob = (_loaded_newgrf_features.has_newhouses ? hs->probability : 1);
01963 probability_max += cur_prob;
01964 probs[num] = cur_prob;
01965 houses[num++] = (HouseID)i;
01966 }
01967
01968 uint maxz = GetTileMaxZ(tile);
01969
01970 while (probability_max > 0) {
01971 uint r = RandomRange(probability_max);
01972 uint i;
01973 for (i = 0; i < num; i++) {
01974 if (probs[i] > r) break;
01975 r -= probs[i];
01976 }
01977
01978 HouseID house = houses[i];
01979 probability_max -= probs[i];
01980
01981
01982 num--;
01983 houses[i] = houses[num];
01984 probs[i] = probs[num];
01985
01986 const HouseSpec *hs = GetHouseSpecs(house);
01987
01988 if (_loaded_newgrf_features.has_newhouses) {
01989 if (hs->override != 0) {
01990 house = hs->override;
01991 hs = GetHouseSpecs(house);
01992 }
01993
01994 if ((hs->extra_flags & BUILDING_IS_HISTORICAL) && !_generating_world && _game_mode != GM_EDITOR) continue;
01995 }
01996
01997 if (_cur_year < hs->min_year || _cur_year > hs->max_year) continue;
01998
01999
02000 uint oneof = 0;
02001
02002 if (hs->building_flags & BUILDING_IS_CHURCH) {
02003 SetBit(oneof, TOWN_HAS_CHURCH);
02004 } else if (hs->building_flags & BUILDING_IS_STADIUM) {
02005 SetBit(oneof, TOWN_HAS_STADIUM);
02006 }
02007
02008 if (HASBITS(t->flags12, oneof)) continue;
02009
02010
02011 bool noslope = (hs->building_flags & TILE_NOT_SLOPED) != 0;
02012 if (noslope && slope != SLOPE_FLAT) continue;
02013
02014 if (hs->building_flags & TILE_SIZE_2x2) {
02015 if (!CheckTownBuild2x2House(&tile, t, maxz, noslope)) continue;
02016 } else if (hs->building_flags & TILE_SIZE_2x1) {
02017 if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SW)) continue;
02018 } else if (hs->building_flags & TILE_SIZE_1x2) {
02019 if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SE)) continue;
02020 } else {
02021
02022 }
02023
02024 if (HasBit(hs->callback_mask, CBM_HOUSE_ALLOW_CONSTRUCTION)) {
02025 uint16 callback_res = GetHouseCallback(CBID_HOUSE_ALLOW_CONSTRUCTION, 0, 0, house, t, tile);
02026 if (callback_res != CALLBACK_FAILED && GB(callback_res, 0, 8) == 0) continue;
02027 }
02028
02029
02030 t->num_houses++;
02031
02032
02033 t->flags12 |= oneof;
02034
02035 byte construction_counter = 0;
02036 byte construction_stage = 0;
02037
02038 if (_generating_world || _game_mode == GM_EDITOR) {
02039 uint32 r = Random();
02040
02041 construction_stage = TOWN_HOUSE_COMPLETED;
02042 if (Chance16(1, 7)) construction_stage = GB(r, 0, 2);
02043
02044 if (construction_stage == TOWN_HOUSE_COMPLETED) {
02045 ChangePopulation(t, hs->population);
02046 } else {
02047 construction_counter = GB(r, 2, 2);
02048 }
02049 }
02050
02051 MakeTownHouse(tile, t, construction_counter, construction_stage, house, Random());
02052
02053 return true;
02054 }
02055
02056 return false;
02057 }
02058
02065 static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
02066 {
02067 assert(IsTileType(tile, MP_HOUSE));
02068 DecreaseBuildingCount(t, house);
02069 DoClearSquare(tile);
02070 DeleteAnimatedTile(tile);
02071 }
02072
02080 TileIndexDiff GetHouseNorthPart(HouseID &house)
02081 {
02082 if (house >= 3) {
02083 if (GetHouseSpecs(house - 1)->building_flags & TILE_SIZE_2x1) {
02084 house--;
02085 return TileDiffXY(-1, 0);
02086 } else if (GetHouseSpecs(house - 1)->building_flags & BUILDING_2_TILES_Y) {
02087 house--;
02088 return TileDiffXY(0, -1);
02089 } else if (GetHouseSpecs(house - 2)->building_flags & BUILDING_HAS_4_TILES) {
02090 house -= 2;
02091 return TileDiffXY(-1, 0);
02092 } else if (GetHouseSpecs(house - 3)->building_flags & BUILDING_HAS_4_TILES) {
02093 house -= 3;
02094 return TileDiffXY(-1, -1);
02095 }
02096 }
02097 return 0;
02098 }
02099
02100 void ClearTownHouse(Town *t, TileIndex tile)
02101 {
02102 assert(IsTileType(tile, MP_HOUSE));
02103
02104 HouseID house = GetHouseType(tile);
02105
02106
02107 tile += GetHouseNorthPart(house);
02108
02109 const HouseSpec *hs = GetHouseSpecs(house);
02110
02111
02112 if (IsHouseCompleted(tile)) {
02113 ChangePopulation(t, -hs->population);
02114 }
02115
02116 t->num_houses--;
02117
02118
02119 if (hs->building_flags & BUILDING_IS_CHURCH) {
02120 ClrBit(t->flags12, TOWN_HAS_CHURCH);
02121 } else if (hs->building_flags & BUILDING_IS_STADIUM) {
02122 ClrBit(t->flags12, TOWN_HAS_STADIUM);
02123 }
02124
02125
02126 uint eflags = hs->building_flags;
02127 DoClearTownHouseHelper(tile, t, house);
02128 if (eflags & BUILDING_2_TILES_Y) DoClearTownHouseHelper(tile + TileDiffXY(0, 1), t, ++house);
02129 if (eflags & BUILDING_2_TILES_X) DoClearTownHouseHelper(tile + TileDiffXY(1, 0), t, ++house);
02130 if (eflags & BUILDING_HAS_4_TILES) DoClearTownHouseHelper(tile + TileDiffXY(1, 1), t, ++house);
02131 }
02132
02133 static bool IsUniqueTownName(const char *name)
02134 {
02135 const Town *t;
02136
02137 FOR_ALL_TOWNS(t) {
02138 if (t->name != NULL && strcmp(t->name, name) == 0) return false;
02139 }
02140
02141 return true;
02142 }
02143
02150 CommandCost CmdRenameTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02151 {
02152 if (!IsValidTownID(p1)) return CMD_ERROR;
02153
02154 bool reset = StrEmpty(text);
02155
02156 if (!reset) {
02157 if (strlen(text) >= MAX_LENGTH_TOWN_NAME_BYTES) return CMD_ERROR;
02158 if (!IsUniqueTownName(text)) return_cmd_error(STR_NAME_MUST_BE_UNIQUE);
02159 }
02160
02161 if (flags & DC_EXEC) {
02162 Town *t = GetTown(p1);
02163
02164 free(t->name);
02165 t->name = reset ? NULL : strdup(text);
02166
02167 UpdateTownVirtCoord(t);
02168 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
02169 UpdateAllStationVirtCoord();
02170 UpdateAllWaypointSigns();
02171 MarkWholeScreenDirty();
02172 }
02173 return CommandCost();
02174 }
02175
02177 void ExpandTown(Town *t)
02178 {
02179
02180
02181 static bool warned_no_roads = false;
02182 if (!_settings_game.economy.allow_town_roads && !warned_no_roads) {
02183 ShowErrorMessage(INVALID_STRING_ID, STR_TOWN_EXPAND_WARN_NO_ROADS, 0, 0);
02184 warned_no_roads = true;
02185 }
02186
02187
02188 uint amount = RandomRange(ClampToU16(t->num_houses / 10)) + 3;
02189 t->num_houses += amount;
02190 UpdateTownRadius(t);
02191
02192 uint n = amount * 10;
02193 do GrowTown(t); while (--n);
02194
02195 t->num_houses -= amount;
02196 UpdateTownRadius(t);
02197
02198 UpdateTownMaxPass(t);
02199 }
02200
02201 extern const byte _town_action_costs[8] = {
02202 2, 4, 9, 35, 48, 53, 117, 175
02203 };
02204
02205 static void TownActionAdvertiseSmall(Town *t)
02206 {
02207 ModifyStationRatingAround(t->xy, _current_company, 0x40, 10);
02208 }
02209
02210 static void TownActionAdvertiseMedium(Town *t)
02211 {
02212 ModifyStationRatingAround(t->xy, _current_company, 0x70, 15);
02213 }
02214
02215 static void TownActionAdvertiseLarge(Town *t)
02216 {
02217 ModifyStationRatingAround(t->xy, _current_company, 0xA0, 20);
02218 }
02219
02220 static void TownActionRoadRebuild(Town *t)
02221 {
02222 t->road_build_months = 6;
02223
02224 char company_name[MAX_LENGTH_COMPANY_NAME_BYTES];
02225 SetDParam(0, _current_company);
02226 GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
02227
02228 char *cn = strdup(company_name);
02229 SetDParam(0, t->index);
02230 SetDParamStr(1, cn);
02231
02232 AddNewsItem(STR_2055_TRAFFIC_CHAOS_IN_ROAD_REBUILDING, NS_GENERAL, t->xy, 0, cn);
02233 }
02234
02235 static bool DoBuildStatueOfCompany(TileIndex tile, TownID town_id)
02236 {
02237
02238 if (IsSteepSlope(GetTileSlope(tile, NULL))) return false;
02239
02240 if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return false;
02241
02242 if (!IsTileType(tile, MP_HOUSE) &&
02243 !IsTileType(tile, MP_CLEAR) &&
02244 !IsTileType(tile, MP_TREES)) {
02245 return false;
02246 }
02247
02248 CompanyID old = _current_company;
02249 _current_company = OWNER_NONE;
02250 CommandCost r = DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
02251 _current_company = old;
02252
02253 if (CmdFailed(r)) return false;
02254
02255 MakeStatue(tile, _current_company, town_id);
02256 MarkTileDirtyByTile(tile);
02257
02258 return true;
02259 }
02260
02267 static bool SearchTileForStatue(TileIndex tile, void *user_data)
02268 {
02269 TownID *town_id = (TownID *)user_data;
02270 return DoBuildStatueOfCompany(tile, *town_id);
02271 }
02272
02278 static void TownActionBuildStatue(Town *t)
02279 {
02280 TileIndex tile = t->xy;
02281
02282 if (CircularTileSearch(&tile, 9, SearchTileForStatue, &t->index)) {
02283 SetBit(t->statues, _current_company);
02284 }
02285 }
02286
02287 static void TownActionFundBuildings(Town *t)
02288 {
02289
02290 t->grow_counter = 1;
02291
02292 SetBit(t->flags12, TOWN_IS_FUNDED);
02293
02294 t->fund_buildings_months = 3;
02295 }
02296
02297 static void TownActionBuyRights(Town *t)
02298 {
02299
02300 if (!_settings_game.economy.exclusive_rights) return;
02301
02302 t->exclusive_counter = 12;
02303 t->exclusivity = _current_company;
02304
02305 ModifyStationRatingAround(t->xy, _current_company, 130, 17);
02306 }
02307
02308 static void TownActionBribe(Town *t)
02309 {
02310 if (Chance16(1, 14)) {
02311
02312 t->unwanted[_current_company] = 6;
02313
02314
02315 Station *st;
02316 FOR_ALL_STATIONS(st) {
02317 if (st->town == t && st->owner == _current_company) {
02318 for (CargoID i = 0; i < NUM_CARGO; i++) st->goods[i].rating = 0;
02319 }
02320 }
02321
02322
02323
02324 if (IsLocalCompany()) ShowErrorMessage(STR_BRIBE_FAILED_2, STR_BRIBE_FAILED, 0, 0);
02325
02326
02327
02328
02329
02330 if (t->ratings[_current_company] > RATING_BRIBE_DOWN_TO) {
02331 t->ratings[_current_company] = RATING_BRIBE_DOWN_TO;
02332 InvalidateWindow(WC_TOWN_AUTHORITY, t->index);
02333 }
02334 } else {
02335 ChangeTownRating(t, RATING_BRIBE_UP_STEP, RATING_BRIBE_MAXIMUM, DC_EXEC);
02336 }
02337 }
02338
02339 typedef void TownActionProc(Town *t);
02340 static TownActionProc * const _town_action_proc[] = {
02341 TownActionAdvertiseSmall,
02342 TownActionAdvertiseMedium,
02343 TownActionAdvertiseLarge,
02344 TownActionRoadRebuild,
02345 TownActionBuildStatue,
02346 TownActionFundBuildings,
02347 TownActionBuyRights,
02348 TownActionBribe
02349 };
02350
02351 enum TownActions {
02352 TACT_NONE = 0x00,
02353
02354 TACT_ADVERTISE_SMALL = 0x01,
02355 TACT_ADVERTISE_MEDIUM = 0x02,
02356 TACT_ADVERTISE_LARGE = 0x04,
02357 TACT_ROAD_REBUILD = 0x08,
02358 TACT_BUILD_STATUE = 0x10,
02359 TACT_FOUND_BUILDINGS = 0x20,
02360 TACT_BUY_RIGHTS = 0x40,
02361 TACT_BRIBE = 0x80,
02362
02363 TACT_ADVERTISE = TACT_ADVERTISE_SMALL | TACT_ADVERTISE_MEDIUM | TACT_ADVERTISE_LARGE,
02364 TACT_CONSTRUCTION = TACT_ROAD_REBUILD | TACT_BUILD_STATUE | TACT_FOUND_BUILDINGS,
02365 TACT_FUNDS = TACT_BUY_RIGHTS | TACT_BRIBE,
02366 TACT_ALL = TACT_ADVERTISE | TACT_CONSTRUCTION | TACT_FUNDS,
02367 };
02368
02369 DECLARE_ENUM_AS_BIT_SET(TownActions);
02370
02377 uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t)
02378 {
02379 int num = 0;
02380 TownActions buttons = TACT_NONE;
02381
02382
02383 if (cid != COMPANY_SPECTATOR && !(_settings_game.economy.bribe && t->unwanted[cid])) {
02384
02385
02386 Money avail = GetCompany(cid)->money + _price.station_value * 200;
02387 Money ref = _price.build_industry >> 8;
02388
02389
02390
02391 for (uint i = 0; i != lengthof(_town_action_costs); i++) {
02392 const TownActions cur = (TownActions)(1 << i);
02393
02394
02395 if (cur == TACT_BRIBE && (!_settings_game.economy.bribe || t->ratings[cid] >= RATING_BRIBE_MAXIMUM))
02396 continue;
02397
02398
02399 if (cur == TACT_BUY_RIGHTS && !_settings_game.economy.exclusive_rights)
02400 continue;
02401
02402
02403 if (cur == TACT_BUILD_STATUE && HasBit(t->statues, cid))
02404 continue;
02405
02406 if (avail >= _town_action_costs[i] * ref) {
02407 buttons |= cur;
02408 num++;
02409 }
02410 }
02411 }
02412
02413 if (nump != NULL) *nump = num;
02414 return buttons;
02415 }
02416
02425 CommandCost CmdDoTownAction(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02426 {
02427 if (!IsValidTownID(p1) || p2 >= lengthof(_town_action_proc)) return CMD_ERROR;
02428
02429 Town *t = GetTown(p1);
02430
02431 if (!HasBit(GetMaskOfTownActions(NULL, _current_company, t), p2)) return CMD_ERROR;
02432
02433 CommandCost cost(EXPENSES_OTHER, (_price.build_industry >> 8) * _town_action_costs[p2]);
02434
02435 if (flags & DC_EXEC) {
02436 _town_action_proc[p2](t);
02437 InvalidateWindow(WC_TOWN_AUTHORITY, p1);
02438 }
02439
02440 return cost;
02441 }
02442
02443 static void UpdateTownGrowRate(Town *t)
02444 {
02445
02446 const Company *c;
02447 FOR_ALL_COMPANIES(c) {
02448 if (t->ratings[c->index] < RATING_GROWTH_MAXIMUM) {
02449 t->ratings[c->index] = min((int)RATING_GROWTH_MAXIMUM, t->ratings[c->index] + RATING_GROWTH_UP_STEP);
02450 }
02451 }
02452
02453 int n = 0;
02454
02455 const Station *st;
02456 FOR_ALL_STATIONS(st) {
02457 if (DistanceSquare(st->xy, t->xy) <= t->squared_town_zone_radius[0]) {
02458 if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
02459 n++;
02460 if (IsValidCompanyID(st->owner)) {
02461 int new_rating = t->ratings[st->owner] + RATING_STATION_UP_STEP;
02462 t->ratings[st->owner] = min(new_rating, INT16_MAX);
02463 }
02464 } else {
02465 if (IsValidCompanyID(st->owner)) {
02466 int new_rating = t->ratings[st->owner] + RATING_STATION_DOWN_STEP;
02467 t->ratings[st->owner] = max(new_rating, INT16_MIN);
02468 }
02469 }
02470 }
02471 }
02472
02473
02474 for (uint i = 0; i < MAX_COMPANIES; i++) {
02475 t->ratings[i] = Clamp(t->ratings[i], RATING_MINIMUM, RATING_MAXIMUM);
02476 }
02477
02478 InvalidateWindow(WC_TOWN_AUTHORITY, t->index);
02479
02480 ClrBit(t->flags12, TOWN_IS_FUNDED);
02481 if (_settings_game.economy.town_growth_rate == 0 && t->fund_buildings_months == 0) return;
02482
02485 static const uint16 _grow_count_values[2][6] = {
02486 { 120, 120, 120, 100, 80, 60 },
02487 { 320, 420, 300, 220, 160, 100 }
02488 };
02489
02490 uint16 m;
02491
02492 if (t->fund_buildings_months != 0) {
02493 m = _grow_count_values[0][min(n, 5)];
02494 t->fund_buildings_months--;
02495 } else {
02496 m = _grow_count_values[1][min(n, 5)];
02497 if (n == 0 && !Chance16(1, 12)) return;
02498 }
02499
02500 if (_settings_game.game_creation.landscape == LT_ARCTIC) {
02501 if (TilePixelHeight(t->xy) >= GetSnowLine() && t->act_food == 0 && t->population > 90)
02502 return;
02503 } else if (_settings_game.game_creation.landscape == LT_TROPIC) {
02504 if (GetTropicZone(t->xy) == TROPICZONE_DESERT && (t->act_food == 0 || t->act_water == 0) && t->population > 60)
02505 return;
02506 }
02507
02508
02509
02510 uint growth_multiplier = _settings_game.economy.town_growth_rate != 0 ? _settings_game.economy.town_growth_rate - 1 : 1;
02511
02512 m >>= growth_multiplier;
02513 if (t->larger_town) m /= 2;
02514
02515 t->growth_rate = m / (t->num_houses / 50 + 1);
02516 if (m <= t->grow_counter)
02517 t->grow_counter = m;
02518
02519 SetBit(t->flags12, TOWN_IS_FUNDED);
02520 }
02521
02522 static void UpdateTownAmounts(Town *t)
02523 {
02524
02525 t->pct_pass_transported = t->new_act_pass * 256 / (t->new_max_pass + 1);
02526
02527 t->max_pass = t->new_max_pass; t->new_max_pass = 0;
02528 t->act_pass = t->new_act_pass; t->new_act_pass = 0;
02529 t->act_food = t->new_act_food; t->new_act_food = 0;
02530 t->act_water = t->new_act_water; t->new_act_water = 0;
02531
02532
02533 t->pct_mail_transported = t->new_act_mail * 256 / (t->new_max_mail + 1);
02534 t->max_mail = t->new_max_mail; t->new_max_mail = 0;
02535 t->act_mail = t->new_act_mail; t->new_act_mail = 0;
02536
02537 InvalidateWindow(WC_TOWN_VIEW, t->index);
02538 }
02539
02540 static void UpdateTownUnwanted(Town *t)
02541 {
02542 const Company *c;
02543
02544 FOR_ALL_COMPANIES(c) {
02545 if (t->unwanted[c->index] > 0) t->unwanted[c->index]--;
02546 }
02547 }
02548
02554 bool CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags)
02555 {
02556 if (!IsValidCompanyID(_current_company) || (flags & DC_NO_TEST_TOWN_RATING)) return true;
02557
02558 Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
02559 if (t == NULL) return true;
02560
02561 if (t->ratings[_current_company] > RATING_VERYPOOR) return true;
02562
02563 _error_message = STR_2009_LOCAL_AUTHORITY_REFUSES;
02564 SetDParam(0, t->index);
02565
02566 return false;
02567 }
02568
02569
02570 Town *CalcClosestTownFromTile(TileIndex tile, uint threshold)
02571 {
02572 Town *t;
02573 uint best = threshold;
02574 Town *best_town = NULL;
02575
02576 FOR_ALL_TOWNS(t) {
02577 uint dist = DistanceManhattan(tile, t->xy);
02578 if (dist < best) {
02579 best = dist;
02580 best_town = t;
02581 }
02582 }
02583
02584 return best_town;
02585 }
02586
02587
02588 Town *ClosestTownFromTile(TileIndex tile, uint threshold)
02589 {
02590 switch (GetTileType(tile)) {
02591 case MP_ROAD:
02592 if (!HasTownOwnedRoad(tile)) {
02593 TownID tid = GetTownIndex(tile);
02594 if (tid == (TownID)INVALID_TOWN) {
02595
02596 if (_generating_world) return CalcClosestTownFromTile(tile, threshold);
02597 assert(GetNumTowns() == 0);
02598 return NULL;
02599 }
02600
02601 Town *town = GetTown(tid);
02602 assert(town->IsValid());
02603
02604 if (DistanceManhattan(tile, town->xy) >= threshold) town = NULL;
02605
02606 return town;
02607 }
02608
02609
02610 case MP_HOUSE:
02611 return GetTownByTile(tile);
02612
02613 default:
02614 return CalcClosestTownFromTile(tile, threshold);
02615 }
02616 }
02617
02618 static bool _town_rating_test = false;
02619 SmallMap<const Town *, int, 4> _town_test_ratings;
02620
02621 void SetTownRatingTestMode(bool mode)
02622 {
02623 static int ref_count = 0;
02624 if (mode) {
02625 if (ref_count == 0) {
02626 _town_test_ratings.Clear();
02627 }
02628 ref_count++;
02629 } else {
02630 assert(ref_count > 0);
02631 ref_count--;
02632 }
02633 _town_rating_test = !(ref_count == 0);
02634 }
02635
02636 static int GetRating(const Town *t)
02637 {
02638 if (_town_rating_test) {
02639 SmallMap<const Town *, int>::iterator it = _town_test_ratings.Find(t);
02640 if (it != _town_test_ratings.End()) {
02641 return it->second;
02642 }
02643 }
02644 return t->ratings[_current_company];
02645 }
02646
02654 void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
02655 {
02656
02657 if (t == NULL || (flags & DC_NO_MODIFY_TOWN_RATING) ||
02658 !IsValidCompanyID(_current_company) ||
02659 (_cheats.magic_bulldozer.value && add < 0)) {
02660 return;
02661 }
02662
02663 int rating = GetRating(t);
02664 if (add < 0) {
02665 if (rating > max) {
02666 rating += add;
02667 if (rating < max) rating = max;
02668 }
02669 } else {
02670 if (rating < max) {
02671 rating += add;
02672 if (rating > max) rating = max;
02673 }
02674 }
02675 if (_town_rating_test) {
02676 _town_test_ratings[t] = rating;
02677 } else {
02678 SetBit(t->have_ratings, _current_company);
02679 t->ratings[_current_company] = rating;
02680 InvalidateWindow(WC_TOWN_AUTHORITY, t->index);
02681 }
02682 }
02683
02684
02685 static const int _default_rating_settings [3][3] = {
02686
02687 { 0, 128, 384},
02688 { 48, 192, 480},
02689 { 96, 384, 768},
02690 };
02691
02692 bool CheckforTownRating(DoCommandFlag flags, Town *t, byte type)
02693 {
02694
02695 if (t == NULL || !IsValidCompanyID(_current_company) || _cheats.magic_bulldozer.value)
02696 return true;
02697
02698
02699
02700
02701
02702 int modemod = _default_rating_settings[_settings_game.difficulty.town_council_tolerance][type];
02703
02704 if (GetRating(t) < 16 + modemod && !(flags & DC_NO_TEST_TOWN_RATING)) {
02705 SetDParam(0, t->index);
02706 _error_message = STR_2009_LOCAL_AUTHORITY_REFUSES;
02707 return false;
02708 }
02709
02710 return true;
02711 }
02712
02713 void TownsMonthlyLoop()
02714 {
02715 Town *t;
02716
02717 FOR_ALL_TOWNS(t) {
02718 if (t->road_build_months != 0) t->road_build_months--;
02719
02720 if (t->exclusive_counter != 0)
02721 if (--t->exclusive_counter == 0) t->exclusivity = INVALID_COMPANY;
02722
02723 UpdateTownGrowRate(t);
02724 UpdateTownAmounts(t);
02725 UpdateTownUnwanted(t);
02726 }
02727 }
02728
02729 void TownsYearlyLoop()
02730 {
02731
02732 for (TileIndex t = 0; t < MapSize(); t++) {
02733 if (!IsTileType(t, MP_HOUSE)) continue;
02734 IncrementHouseAge(t);
02735 }
02736 }
02737
02738 void InitializeTowns()
02739 {
02740
02741 _Town_pool.CleanPool();
02742 _Town_pool.AddBlockToPool();
02743
02744 memset(_subsidies, 0, sizeof(_subsidies));
02745 for (Subsidy *s = _subsidies; s != endof(_subsidies); s++) {
02746 s->cargo_type = CT_INVALID;
02747 }
02748
02749 _total_towns = 0;
02750 }
02751
02752 static CommandCost TerraformTile_Town(TileIndex tile, DoCommandFlag flags, uint z_new, Slope tileh_new)
02753 {
02754 if (AutoslopeEnabled()) {
02755 HouseID house = GetHouseType(tile);
02756 GetHouseNorthPart(house);
02757 const HouseSpec *hs = GetHouseSpecs(house);
02758
02759
02760 if (((hs->building_flags & TILE_NOT_SLOPED) == 0) && !IsSteepSlope(tileh_new) &&
02761 (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) return CommandCost(EXPENSES_CONSTRUCTION, _price.terraform);
02762 }
02763
02764 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02765 }
02766
02768 extern const TileTypeProcs _tile_type_town_procs = {
02769 DrawTile_Town,
02770 GetSlopeZ_Town,
02771 ClearTile_Town,
02772 GetAcceptedCargo_Town,
02773 GetTileDesc_Town,
02774 GetTileTrackStatus_Town,
02775 ClickTile_Town,
02776 AnimateTile_Town,
02777 TileLoop_Town,
02778 ChangeTileOwner_Town,
02779 GetProducedCargo_Town,
02780 NULL,
02781 GetFoundation_Town,
02782 TerraformTile_Town,
02783 };
02784
02785 void ResetHouses()
02786 {
02787 memset(&_house_specs, 0, sizeof(_house_specs));
02788 memcpy(&_house_specs, &_original_house_specs, sizeof(_original_house_specs));
02789
02790
02791 _house_mngr.ResetOverride();
02792 }