OpenTTD: src/town_cmd.cpp Source File

OpenTTD

- Main Page
- Related Pages
- Modules
- Namespaces
- Data Structures
- Files

- File List
- Globals

town_cmd.cpp
Go to the documentation of this file.
1 /* $Id: town_cmd.cpp 27105 2015-01-01 21:25:42Z rubidium $ */
2
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
9
12 #include "stdafx.h"
13 #include "road_internal.h" /* Cleaning up road bits */
14 #include "road_cmd.h"
15 #include "landscape.h"
16 #include "viewport_func.h"
17 #include "cmd_helper.h"
18 #include "command_func.h"
19 #include "industry.h"
20 #include "station_base.h"
21 #include "company_base.h"
22 #include "news_func.h"
23 #include "error.h"
24 #include "object.h"
25 #include "genworld.h"
26 #include "newgrf_debug.h"
27 #include "newgrf_house.h"
28 #include "newgrf_text.h"
29 #include "autoslope.h"
30 #include "tunnelbridge_map.h"
31 #include "strings_func.h"
32 #include "window_func.h"
33 #include "string_func.h"
34 #include "newgrf_cargo.h"
35 #include "cheat_type.h"
36 #include "animated_tile_func.h"
37 #include "date_func.h"
38 #include "subsidy_func.h"
39 #include "core/pool_func.hpp"
40 #include "town.h"
41 #include "townname_func.h"
42 #include "core/random_func.hpp"
43 #include "core/backup_type.hpp"
44 #include "depot_base.h"
45 #include "object_map.h"
46 #include "object_base.h"
47 #include "ai/ai.hpp"
48 #include "game/game.hpp"
49
50 #include "table/strings.h"
51 #include "table/town_land.h"
52
53 #include "safeguards.h"
54
55 TownID _new_town_id;
56 uint32 _town_cargoes_accepted;
57
58 /* Initialize the town-pool */
59 TownPool _town_pool("Town");
60 INSTANTIATE_POOL_METHODS(Town)
61
62 Town::~Town()
63 {
64 free(this->name);
65 free(this->text);
66
67 if (CleaningPool()) return;
68
69 /* Delete town authority window
70 * and remove from list of sorted towns */
71 DeleteWindowById(WC_TOWN_VIEW, this->index);
72
73 /* Check no industry is related to us. */
74 const Industry *i;
75 FOR_ALL_INDUSTRIES(i) assert(i->town != this);
76
77 /* ... and no object is related to us. */
78 const Object *o;
79 FOR_ALL_OBJECTS(o) assert(o->town != this);
80
81 /* Check no tile is related to us. */
82 for (TileIndex tile = 0; tile < MapSize(); ++tile) {
83 switch (GetTileType(tile)) {
84 case MP_HOUSE:
85 assert(GetTownIndex(tile) != this->index);
86 break;
87
88 case MP_ROAD:
89 assert(!HasTownOwnedRoad(tile) || GetTownIndex(tile) != this->index);
90 break;
91
92 case MP_TUNNELBRIDGE:
93 assert(!IsTileOwner(tile, OWNER_TOWN) || ClosestTownFromTile(tile, UINT_MAX) != this);
94 break;
95
96 default:
97 break;
98 }
99 }
100
101 /* Clear the persistent storage list. */
102 this->psa_list.clear();
103
104 DeleteSubsidyWith(ST_TOWN, this->index);
105 DeleteNewGRFInspectWindow(GSF_FAKE_TOWNS, this->index);
106 CargoPacket::InvalidateAllFrom(ST_TOWN, this->index);
107 MarkWholeScreenDirty();
108 }
109
110
116 void Town::PostDestructor(size_t index)
117 {
118 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
119 UpdateNearestTownForRoadTiles(false);
120
121 /* Give objects a new home! */
122 Object *o;
123 FOR_ALL_OBJECTS(o) {
124 if (o->town == NULL) o->town = CalcClosestTownFromTile(o->location.tile, UINT_MAX);
125 }
126 }
127
131 void Town::InitializeLayout(TownLayout layout)
132 {
133 if (layout != TL_RANDOM) {
134 this->layout = layout;
135 return;
136 }
137
138 this->layout = TileHash(TileX(this->xy), TileY(this->xy)) % (NUM_TLS - 1);
139 }
140
145 /* static */ Town *Town::GetRandom()
146 {
147 if (Town::GetNumItems() == 0) return NULL;
148 int num = RandomRange((uint16)Town::GetNumItems());
149 size_t index = MAX_UVALUE(size_t);
150
151 while (num >= 0) {
152 num--;
153 index++;
154
155 /* Make sure we have a valid town */
156 while (!Town::IsValidID(index)) {
157 index++;
158 assert(index < Town::GetPoolSize());
159 }
160 }
161
162 return Town::Get(index);
163 }
164
169 Money HouseSpec::GetRemovalCost() const
170 {
171 return (_price[PR_CLEAR_HOUSE] * this->removal_cost) >> 8;
172 }
173
174 /* Local */
175 static int _grow_town_result;
176
177 /* Describe the possible states */
178 enum TownGrowthResult {
179 GROWTH_SUCCEED = -1,
180 GROWTH_SEARCH_STOPPED = 0
181 // GROWTH_SEARCH_RUNNING >= 1
182 };
183
184 static bool BuildTownHouse(Town *t, TileIndex tile);
185 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout);
186
187 static void TownDrawHouseLift(const TileInfo *ti)
188 {
189 AddChildSpriteScreen(SPR_LIFT, PAL_NONE, 14, 60 - GetLiftPosition(ti->tile));
190 }
191
192 typedef void TownDrawTileProc(const TileInfo *ti);
193 static TownDrawTileProc * const _town_draw_tile_procs[1] = {
194 TownDrawHouseLift
195 };
196
202 static inline DiagDirection RandomDiagDir()
203 {
204 return (DiagDirection)(3 & Random());
205 }
206
212 static void DrawTile_Town(TileInfo *ti)
213 {
214 HouseID house_id = GetHouseType(ti->tile);
215
216 if (house_id >= NEW_HOUSE_OFFSET) {
217 /* Houses don't necessarily need new graphics. If they don't have a
218 * spritegroup associated with them, then the sprite for the substitute
219 * house id is drawn instead. */
220 if (HouseSpec::Get(house_id)->grf_prop.spritegroup[0] != NULL) {
221 DrawNewHouseTile(ti, house_id);
222 return;
223 } else {
224 house_id = HouseSpec::Get(house_id)->grf_prop.subst_id;
225 }
226 }
227
228 /* Retrieve pointer to the draw town tile struct */
229 const DrawBuildingsTileStruct *dcts = &_town_draw_tile_data[house_id << 4 | TileHash2Bit(ti->x, ti->y) << 2 | GetHouseBuildingStage(ti->tile)];
230
231 if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
232
233 DrawGroundSprite(dcts->ground.sprite, dcts->ground.pal);
234
235 /* If houses are invisible, do not draw the upper part */
236 if (IsInvisibilitySet(TO_HOUSES)) return;
237
238 /* Add a house on top of the ground? */
239 SpriteID image = dcts->building.sprite;
240 if (image != 0) {
241 AddSortableSpriteToDraw(image, dcts->building.pal,
242 ti->x + dcts->subtile_x,
243 ti->y + dcts->subtile_y,
244 dcts->width,
245 dcts->height,
246 dcts->dz,
247 ti->z,
248 IsTransparencySet(TO_HOUSES)
249 );
250
251 if (IsTransparencySet(TO_HOUSES)) return;
252 }
253
254 {
255 int proc = dcts->draw_proc - 1;
256
257 if (proc >= 0) _town_draw_tile_procs[proc](ti);
258 }
259 }
260
261 static int GetSlopePixelZ_Town(TileIndex tile, uint x, uint y)
262 {
263 return GetTileMaxPixelZ(tile);
264 }
265
267 static Foundation GetFoundation_Town(TileIndex tile, Slope tileh)
268 {
269 HouseID hid = GetHouseType(tile);
270
271 /* For NewGRF house tiles we might not be drawing a foundation. We need to
272 * account for this, as other structures should
273 * draw the wall of the foundation in this case.
274 */
275 if (hid >= NEW_HOUSE_OFFSET) {
276 const HouseSpec *hs = HouseSpec::Get(hid);
277 if (hs->grf_prop.spritegroup[0] != NULL && HasBit(hs->callback_mask, CBM_HOUSE_DRAW_FOUNDATIONS)) {
278 uint32 callback_res = GetHouseCallback(CBID_HOUSE_DRAW_FOUNDATIONS, 0, 0, hid, Town::GetByTile(tile), tile);
279 if (callback_res != CALLBACK_FAILED && !ConvertBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_DRAW_FOUNDATIONS, callback_res)) return FOUNDATION_NONE;
280 }
281 }
282 return FlatteningFoundation(tileh);
283 }
284
291 static void AnimateTile_Town(TileIndex tile)
292 {
293 if (GetHouseType(tile) >= NEW_HOUSE_OFFSET) {
294 AnimateNewHouseTile(tile);
295 return;
296 }
297
298 if (_tick_counter & 3) return;
299
300 /* If the house is not one with a lift anymore, then stop this animating.
301 * Not exactly sure when this happens, but probably when a house changes.
302 * Before this was just a return...so it'd leak animated tiles..
303 * That bug seems to have been here since day 1?? */
304 if (!(HouseSpec::Get(GetHouseType(tile))->building_flags & BUILDING_IS_ANIMATED)) {
305 DeleteAnimatedTile(tile);
306 return;
307 }
308
309 if (!LiftHasDestination(tile)) {
310 uint i;
311
312 /* Building has 6 floors, number 0 .. 6, where 1 is illegal.
313 * This is due to the fact that the first floor is, in the graphics,
314 * the height of 2 'normal' floors.
315 * Furthermore, there are 6 lift positions from floor N (incl) to floor N + 1 (excl) */
316 do {
317 i = RandomRange(7);
318 } while (i == 1 || i * 6 == GetLiftPosition(tile));
319
320 SetLiftDestination(tile, i);
321 }
322
323 int pos = GetLiftPosition(tile);
324 int dest = GetLiftDestination(tile) * 6;
325 pos += (pos < dest) ? 1 : -1;
326 SetLiftPosition(tile, pos);
327
328 if (pos == dest) {
329 HaltLift(tile);
330 DeleteAnimatedTile(tile);
331 }
332
333 MarkTileDirtyByTile(tile);
334 }
335
342 static bool IsCloseToTown(TileIndex tile, uint dist)
343 {
344 /* On a large map with many towns, it may be faster to check the surroundings of the tile.
345 * An iteration in TILE_AREA_LOOP() is generally 2 times faster than one in FOR_ALL_TOWNS(). */
346 if (Town::GetNumItems() > (size_t) (dist * dist * 2)) {
347 const int tx = TileX(tile);
348 const int ty = TileY(tile);
349 TileArea tile_area = TileArea(
350 TileXY(max(0, tx - (int) dist), max(0, ty - (int) dist)),
351 TileXY(min(MapMaxX(), tx + (int) dist), min(MapMaxY(), ty + (int) dist))
352 );
353 TILE_AREA_LOOP(atile, tile_area) {
354 if (GetTileType(atile) == MP_HOUSE) {
355 Town *t = Town::GetByTile(atile);
356 if (DistanceManhattan(tile, t->xy) < dist) return true;
357 }
358 }
359 return false;
360 }
361
362 const Town *t;
363
364 FOR_ALL_TOWNS(t) {
365 if (DistanceManhattan(tile, t->xy) < dist) return true;
366 }
367 return false;
368 }
369
374 void Town::UpdateVirtCoord()
375 {
376 Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
377 SetDParam(0, this->index);
378 SetDParam(1, this->cache.population);
379 this->cache.sign.UpdatePosition(pt.x, pt.y - 24 * ZOOM_LVL_BASE,
380 _settings_client.gui.population_in_label ? STR_VIEWPORT_TOWN_POP : STR_VIEWPORT_TOWN);
381
382 SetWindowDirty(WC_TOWN_VIEW, this->index);
383 }
384
386 void UpdateAllTownVirtCoords()
387 {
388 Town *t;
389
390 FOR_ALL_TOWNS(t) {
391 t->UpdateVirtCoord();
392 }
393 }
394
400 static void ChangePopulation(Town *t, int mod)
401 {
402 t->cache.population += mod;
403 InvalidateWindowData(WC_TOWN_VIEW, t->index); // Cargo requirements may appear/vanish for small populations
404 t->UpdateVirtCoord();
405
406 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
407 }
408
414 uint32 GetWorldPopulation()
415 {
416 uint32 pop = 0;
417 const Town *t;
418
419 FOR_ALL_TOWNS(t) pop += t->cache.population;
420 return pop;
421 }
422
427 static void MakeSingleHouseBigger(TileIndex tile)
428 {
429 assert(IsTileType(tile, MP_HOUSE));
430
431 /* progress in construction stages */
432 IncHouseConstructionTick(tile);
433 if (GetHouseConstructionTick(tile) != 0) return;
434
435 AnimateNewHouseConstruction(tile);
436
437 if (IsHouseCompleted(tile)) {
438 /* Now that construction is complete, we can add the population of the
439 * building to the town. */
440 ChangePopulation(Town::GetByTile(tile), HouseSpec::Get(GetHouseType(tile))->population);
441 ResetHouseAge(tile);
442 }
443 MarkTileDirtyByTile(tile);
444 }
445
450 static void MakeTownHouseBigger(TileIndex tile)
451 {
452 uint flags = HouseSpec::Get(GetHouseType(tile))->building_flags;
453 if (flags & BUILDING_HAS_1_TILE) MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 0));
454 if (flags & BUILDING_2_TILES_Y) MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 1));
455 if (flags & BUILDING_2_TILES_X) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 0));
456 if (flags & BUILDING_HAS_4_TILES) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 1));
457 }
458
465 static void TileLoop_Town(TileIndex tile)
466 {
467 HouseID house_id = GetHouseType(tile);
468
469 /* NewHouseTileLoop returns false if Callback 21 succeeded, i.e. the house
470 * doesn't exist any more, so don't continue here. */
471 if (house_id >= NEW_HOUSE_OFFSET && !NewHouseTileLoop(tile)) return;
472
473 if (!IsHouseCompleted(tile)) {
474 /* Construction is not completed. See if we can go further in construction*/
475 MakeTownHouseBigger(tile);
476 return;
477 }
478
479 const HouseSpec *hs = HouseSpec::Get(house_id);
480
481 /* If the lift has a destination, it is already an animated tile. */
482 if ((hs->building_flags & BUILDING_IS_ANIMATED) &&
483 house_id < NEW_HOUSE_OFFSET &&
484 !LiftHasDestination(tile) &&
485 Chance16(1, 2)) {
486 AddAnimatedTile(tile);
487 }
488
489 Town *t = Town::GetByTile(tile);
490 uint32 r = Random();
491
492 StationFinder stations(TileArea(tile, 1, 1));
493
494 if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
495 for (uint i = 0; i < 256; i++) {
496 uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, r, house_id, t, tile);
497
498 if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
499
500 CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
501 if (cargo == CT_INVALID) continue;
502
503 uint amt = GB(callback, 0, 8);
504 if (amt == 0) continue;
505
506 uint moved = MoveGoodsToStation(cargo, amt, ST_TOWN, t->index, stations.GetStations());
507
508 const CargoSpec *cs = CargoSpec::Get(cargo);
509 t->supplied[cs->Index()].new_max += amt;
510 t->supplied[cs->Index()].new_act += moved;
511 }
512 } else {
513 if (GB(r, 0, 8) < hs->population) {
514 uint amt = GB(r, 0, 8) / 8 + 1;
515
516 if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
517 t->supplied[CT_PASSENGERS].new_max += amt;
518 t->supplied[CT_PASSENGERS].new_act += MoveGoodsToStation(CT_PASSENGERS, amt, ST_TOWN, t->index, stations.GetStations());
519 }
520
521 if (GB(r, 8, 8) < hs->mail_generation) {
522 uint amt = GB(r, 8, 8) / 8 + 1;
523
524 if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
525 t->supplied[CT_MAIL].new_max += amt;
526 t->supplied[CT_MAIL].new_act += MoveGoodsToStation(CT_MAIL, amt, ST_TOWN, t->index, stations.GetStations());
527 }
528 }
529
530 Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
531
532 if ((hs->building_flags & BUILDING_HAS_1_TILE) &&
533 HasBit(t->flags, TOWN_IS_GROWING) &&
534 CanDeleteHouse(tile) &&
535 GetHouseAge(tile) >= hs->minimum_life &&
536 --t->time_until_rebuild == 0) {
537 t->time_until_rebuild = GB(r, 16, 8) + 192;
538
539 ClearTownHouse(t, tile);
540
541 /* Rebuild with another house? */
542 if (GB(r, 24, 8) >= 12) BuildTownHouse(t, tile);
543 }
544
545 cur_company.Restore();
546 }
547
548 static CommandCost ClearTile_Town(TileIndex tile, DoCommandFlag flags)
549 {
550 if (flags & DC_AUTO) return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
551 if (!CanDeleteHouse(tile)) return CMD_ERROR;
552
553 const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
554
555 CommandCost cost(EXPENSES_CONSTRUCTION);
556 cost.AddCost(hs->GetRemovalCost());
557
558 int rating = hs->remove_rating_decrease;
559 Town *t = Town::GetByTile(tile);
560
561 if (Company::IsValidID(_current_company)) {
562 if (rating > t->ratings[_current_company] && !(flags & DC_NO_TEST_TOWN_RATING) && !_cheats.magic_bulldozer.value) {
563 SetDParam(0, t->index);
564 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
565 }
566 }
567
568 ChangeTownRating(t, -rating, RATING_HOUSE_MINIMUM, flags);
569 if (flags & DC_EXEC) {
570 ClearTownHouse(t, tile);
571 }
572
573 return cost;
574 }
575
576 static void AddProducedCargo_Town(TileIndex tile, CargoArray &produced)
577 {
578 HouseID house_id = GetHouseType(tile);
579 const HouseSpec *hs = HouseSpec::Get(house_id);
580 Town *t = Town::GetByTile(tile);
581
582 if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
583 for (uint i = 0; i < 256; i++) {
584 uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, 0, house_id, t, tile);
585
586 if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
587
588 CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
589
590 if (cargo == CT_INVALID) continue;
591 produced[cargo]++;
592 }
593 } else {
594 if (hs->population > 0) {
595 produced[CT_PASSENGERS]++;
596 }
597 if (hs->mail_generation > 0) {
598 produced[CT_MAIL]++;
599 }
600 }
601 }
602
603 static inline void AddAcceptedCargoSetMask(CargoID cargo, uint amount, CargoArray &acceptance, uint32 *always_accepted)
604 {
605 if (cargo == CT_INVALID || amount == 0) return;
606 acceptance[cargo] += amount;
607 SetBit(*always_accepted, cargo);
608 }
609
610 static void AddAcceptedCargo_Town(TileIndex tile, CargoArray &acceptance, uint32 *always_accepted)
611 {
612 const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
613 CargoID accepts[3];
614
615 /* Set the initial accepted cargo types */
616 for (uint8 i = 0; i < lengthof(accepts); i++) {
617 accepts[i] = hs->accepts_cargo[i];
618 }
619
620 /* Check for custom accepted cargo types */
621 if (HasBit(hs->callback_mask, CBM_HOUSE_ACCEPT_CARGO)) {
622 uint16 callback = GetHouseCallback(CBID_HOUSE_ACCEPT_CARGO, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
623 if (callback != CALLBACK_FAILED) {
624 /* Replace accepted cargo types with translated values from callback */
625 accepts[0] = GetCargoTranslation(GB(callback, 0, 5), hs->grf_prop.grffile);
626 accepts[1] = GetCargoTranslation(GB(callback, 5, 5), hs->grf_prop.grffile);
627 accepts[2] = GetCargoTranslation(GB(callback, 10, 5), hs->grf_prop.grffile);
628 }
629 }
630
631 /* Check for custom cargo acceptance */
632 if (HasBit(hs->callback_mask, CBM_HOUSE_CARGO_ACCEPTANCE)) {
633 uint16 callback = GetHouseCallback(CBID_HOUSE_CARGO_ACCEPTANCE, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
634 if (callback != CALLBACK_FAILED) {
635 AddAcceptedCargoSetMask(accepts[0], GB(callback, 0, 4), acceptance, always_accepted);
636 AddAcceptedCargoSetMask(accepts[1], GB(callback, 4, 4), acceptance, always_accepted);
637 if (_settings_game.game_creation.landscape != LT_TEMPERATE && HasBit(callback, 12)) {
638 /* The 'S' bit indicates food instead of goods */
639 AddAcceptedCargoSetMask(CT_FOOD, GB(callback, 8, 4), acceptance, always_accepted);
640 } else {
641 AddAcceptedCargoSetMask(accepts[2], GB(callback, 8, 4), acceptance, always_accepted);
642 }
643 return;
644 }
645 }
646
647 /* No custom acceptance, so fill in with the default values */
648 for (uint8 i = 0; i < lengthof(accepts); i++) {
649 AddAcceptedCargoSetMask(accepts[i], hs->cargo_acceptance[i], acceptance, always_accepted);
650 }
651 }
652
653 static void GetTileDesc_Town(TileIndex tile, TileDesc *td)
654 {
655 const HouseID house = GetHouseType(tile);
656 const HouseSpec *hs = HouseSpec::Get(house);
657 bool house_completed = IsHouseCompleted(tile);
658
659 td->str = hs->building_name;
660
661 uint16 callback_res = GetHouseCallback(CBID_HOUSE_CUSTOM_NAME, house_completed ? 1 : 0, 0, house, Town::GetByTile(tile), tile);
662 if (callback_res != CALLBACK_FAILED && callback_res != 0x400) {
663 if (callback_res > 0x400) {
664 ErrorUnknownCallbackResult(hs->grf_prop.grffile->grfid, CBID_HOUSE_CUSTOM_NAME, callback_res);
665 } else {
666 StringID new_name = GetGRFStringID(hs->grf_prop.grffile->grfid, 0xD000 + callback_res);
667 if (new_name != STR_NULL && new_name != STR_UNDEFINED) {
668 td->str = new_name;
669 }
670 }
671 }
672
673 if (!house_completed) {
674 SetDParamX(td->dparam, 0, td->str);
675 td->str = STR_LAI_TOWN_INDUSTRY_DESCRIPTION_UNDER_CONSTRUCTION;
676 }
677
678 if (hs->grf_prop.grffile != NULL) {
679 const GRFConfig *gc = GetGRFConfig(hs->grf_prop.grffile->grfid);
680 td->grf = gc->GetName();
681 }
682
683 td->owner[0] = OWNER_TOWN;
684 }
685
686 static TrackStatus GetTileTrackStatus_Town(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
687 {
688 /* not used */
689 return 0;
690 }
691
692 static void ChangeTileOwner_Town(TileIndex tile, Owner old_owner, Owner new_owner)
693 {
694 /* not used */
695 }
696
700 void UpdateTownCargoTotal(Town *t)
701 {
702 t->cargo_accepted_total = 0;
703
704 const TileArea &area = t->cargo_accepted.GetArea();
705 TILE_AREA_LOOP(tile, area) {
706 if (TileX(tile) % AcceptanceMatrix::GRID == 0 && TileY(tile) % AcceptanceMatrix::GRID == 0) {
707 t->cargo_accepted_total |= t->cargo_accepted[tile];
708 }
709 }
710 }
711
718 static void UpdateTownCargoes(Town *t, TileIndex start, bool update_total = true)
719 {
720 CargoArray accepted, produced;
721 uint32 dummy;
722
723 /* Gather acceptance for all houses in an area around the start tile.
724 * The area is composed of the square the tile is in, extended one square in all
725 * directions as the coverage area of a single station is bigger than just one square. */
726 TileArea area = AcceptanceMatrix::GetAreaForTile(start, 1);
727 TILE_AREA_LOOP(tile, area) {
728 if (!IsTileType(tile, MP_HOUSE) || GetTownIndex(tile) != t->index) continue;
729
730 AddAcceptedCargo_Town(tile, accepted, &dummy);
731 AddProducedCargo_Town(tile, produced);
732 }
733
734 /* Create bitmap of produced and accepted cargoes. */
735 uint32 acc = 0;
736 for (uint cid = 0; cid < NUM_CARGO; cid++) {
737 if (accepted[cid] >= 8) SetBit(acc, cid);
738 if (produced[cid] > 0) SetBit(t->cargo_produced, cid);
739 }
740 t->cargo_accepted[start] = acc;
741
742 if (update_total) UpdateTownCargoTotal(t);
743 }
744
748 void UpdateTownCargoes(Town *t)
749 {
750 t->cargo_produced = 0;
751
752 const TileArea &area = t->cargo_accepted.GetArea();
753 if (area.tile == INVALID_TILE) return;
754
755 /* Update acceptance for each grid square. */
756 TILE_AREA_LOOP(tile, area) {
757 if (TileX(tile) % AcceptanceMatrix::GRID == 0 && TileY(tile) % AcceptanceMatrix::GRID == 0) {
758 UpdateTownCargoes(t, tile, false);
759 }
760 }
761
762 /* Update the total acceptance. */
763 UpdateTownCargoTotal(t);
764 }
765
767 void UpdateTownCargoBitmap()
768 {
769 Town *town;
770 _town_cargoes_accepted = 0;
771
772 FOR_ALL_TOWNS(town) {
773 _town_cargoes_accepted |= town->cargo_accepted_total;
774 }
775 }
776
777 static bool GrowTown(Town *t);
778
779 static void TownTickHandler(Town *t)
780 {
781 if (HasBit(t->flags, TOWN_IS_GROWING)) {
782 int i = t->grow_counter - 1;
783 if (i < 0) {
784 if (GrowTown(t)) {
785 i = t->growth_rate & (~TOWN_GROW_RATE_CUSTOM);
786 } else {
787 i = 0;
788 }
789 }
790 t->grow_counter = i;
791 }
792 }
793
794 void OnTick_Town()
795 {
796 if (_game_mode == GM_EDITOR) return;
797
798 Town *t;
799 FOR_ALL_TOWNS(t) {
800 /* Run town tick at regular intervals, but not all at once. */
801 if ((_tick_counter + t->index) % TOWN_GROWTH_TICKS == 0) {
802 TownTickHandler(t);
803 }
804 }
805 }
806
815 static RoadBits GetTownRoadBits(TileIndex tile)
816 {
817 if (IsRoadDepotTile(tile) || IsStandardRoadStopTile(tile)) return ROAD_NONE;
818
819 return GetAnyRoadBits(tile, ROADTYPE_ROAD, true);
820 }
821
832 static bool IsNeighborRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
833 {
834 if (!IsValidTile(tile)) return false;
835
836 /* Lookup table for the used diff values */
837 const TileIndexDiff tid_lt[3] = {
838 TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90RIGHT)),
839 TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90LEFT)),
840 TileOffsByDiagDir(ReverseDiagDir(dir)),
841 };
842
843 dist_multi = (dist_multi + 1) * 4;
844 for (uint pos = 4; pos < dist_multi; pos++) {
845 /* Go (pos / 4) tiles to the left or the right */
846 TileIndexDiff cur = tid_lt[(pos & 1) ? 0 : 1] * (pos / 4);
847
848 /* Use the current tile as origin, or go one tile backwards */
849 if (pos & 2) cur += tid_lt[2];
850
851 /* Test for roadbit parallel to dir and facing towards the middle axis */
852 if (IsValidTile(tile + cur) &&
853 GetTownRoadBits(TILE_ADD(tile, cur)) & DiagDirToRoadBits((pos & 2) ? dir : ReverseDiagDir(dir))) return true;
854 }
855 return false;
856 }
857
866 static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
867 {
868 if (DistanceFromEdge(tile) == 0) return false;
869
870 /* Prevent towns from building roads under bridges along the bridge. Looks silly. */
871 if (IsBridgeAbove(tile) && GetBridgeAxis(tile) == DiagDirToAxis(dir)) return false;
872
873 /* Check if there already is a road at this point? */
874 if (GetTownRoadBits(tile) == ROAD_NONE) {
875 /* No, try if we are able to build a road piece there.
876 * If that fails clear the land, and if that fails exit.
877 * This is to make sure that we can build a road here later. */
878 if (DoCommand(tile, ((dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? ROAD_Y : ROAD_X), 0, DC_AUTO, CMD_BUILD_ROAD).Failed() &&
879 DoCommand(tile, 0, 0, DC_AUTO, CMD_LANDSCAPE_CLEAR).Failed()) {
880 return false;
881 }
882 }
883
884 Slope cur_slope = _settings_game.construction.build_on_slopes ? GetFoundationSlope(tile) : GetTileSlope(tile);
885 bool ret = !IsNeighborRoadTile(tile, dir, t->layout == TL_ORIGINAL ? 1 : 2);
886 if (cur_slope == SLOPE_FLAT) return ret;
887
888 /* If the tile is not a slope in the right direction, then
889 * maybe terraform some. */
890 Slope desired_slope = (dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? SLOPE_NW : SLOPE_NE;
891 if (desired_slope != cur_slope && ComplementSlope(desired_slope) != cur_slope) {
892 if (Chance16(1, 8)) {
893 CommandCost res = CMD_ERROR;
894 if (!_generating_world && Chance16(1, 10)) {
895 /* Note: Do not replace "^ SLOPE_ELEVATED" with ComplementSlope(). The slope might be steep. */
896 res = DoCommand(tile, Chance16(1, 16) ? cur_slope : cur_slope ^ SLOPE_ELEVATED, 0,
897 DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
898 }
899 if (res.Failed() && Chance16(1, 3)) {
900 /* We can consider building on the slope, though. */
901 return ret;
902 }
903 }
904 return false;
905 }
906 return ret;
907 }
908
909 static bool TerraformTownTile(TileIndex tile, int edges, int dir)
910 {
911 assert(tile < MapSize());
912
913 CommandCost r = DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
914 if (r.Failed() || r.GetCost() >= (_price[PR_TERRAFORM] + 2) * 8) return false;
915 DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER | DC_EXEC, CMD_TERRAFORM_LAND);
916 return true;
917 }
918
919 static void LevelTownLand(TileIndex tile)
920 {
921 assert(tile < MapSize());
922
923 /* Don't terraform if land is plain or if there's a house there. */
924 if (IsTileType(tile, MP_HOUSE)) return;
925 Slope tileh = GetTileSlope(tile);
926 if (tileh == SLOPE_FLAT) return;
927
928 /* First try up, then down */
929 if (!TerraformTownTile(tile, ~tileh & SLOPE_ELEVATED, 1)) {
930 TerraformTownTile(tile, tileh & SLOPE_ELEVATED, 0);
931 }
932 }
933
943 static RoadBits GetTownRoadGridElement(Town *t, TileIndex tile, DiagDirection dir)
944 {
945 /* align the grid to the downtown */
946 TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile); // Vector from downtown to the tile
947 RoadBits rcmd = ROAD_NONE;
948
949 switch (t->layout) {
950 default: NOT_REACHED();
951
952 case TL_2X2_GRID:
953 if ((grid_pos.x % 3) == 0) rcmd |= ROAD_Y;
954 if ((grid_pos.y % 3) == 0) rcmd |= ROAD_X;
955 break;
956
957 case TL_3X3_GRID:
958 if ((grid_pos.x % 4) == 0) rcmd |= ROAD_Y;
959 if ((grid_pos.y % 4) == 0) rcmd |= ROAD_X;
960 break;
961 }
962
963 /* Optimise only X-junctions */
964 if (rcmd != ROAD_ALL) return rcmd;
965
966 RoadBits rb_template;
967
968 switch (GetTileSlope(tile)) {
969 default: rb_template = ROAD_ALL; break;
970 case SLOPE_W: rb_template = ROAD_NW | ROAD_SW; break;
971 case SLOPE_SW: rb_template = ROAD_Y | ROAD_SW; break;
972 case SLOPE_S: rb_template = ROAD_SW | ROAD_SE; break;
973 case SLOPE_SE: rb_template = ROAD_X | ROAD_SE; break;
974 case SLOPE_E: rb_template = ROAD_SE | ROAD_NE; break;
975 case SLOPE_NE: rb_template = ROAD_Y | ROAD_NE; break;
976 case SLOPE_N: rb_template = ROAD_NE | ROAD_NW; break;
977 case SLOPE_NW: rb_template = ROAD_X | ROAD_NW; break;
978 case SLOPE_STEEP_W:
979 case SLOPE_STEEP_S:
980 case SLOPE_STEEP_E:
981 case SLOPE_STEEP_N:
982 rb_template = ROAD_NONE;
983 break;
984 }
985
986 /* Stop if the template is compatible to the growth dir */
987 if (DiagDirToRoadBits(ReverseDiagDir(dir)) & rb_template) return rb_template;
988 /* If not generate a straight road in the direction of the growth */
989 return DiagDirToRoadBits(dir) | DiagDirToRoadBits(ReverseDiagDir(dir));
990 }
991
1002 static bool GrowTownWithExtraHouse(Town *t, TileIndex tile)
1003 {
1004 /* We can't look further than that. */
1005 if (DistanceFromEdge(tile) == 0) return false;
1006
1007 uint counter = 0; // counts the house neighbor tiles
1008
1009 /* Check the tiles E,N,W and S of the current tile for houses */
1010 for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
1011 /* Count both void and house tiles for checking whether there
1012 * are enough houses in the area. This to make it likely that
1013 * houses get build up to the edge of the map. */
1014 switch (GetTileType(TileAddByDiagDir(tile, dir))) {
1015 case MP_HOUSE:
1016 case MP_VOID:
1017 counter++;
1018 break;
1019
1020 default:
1021 break;
1022 }
1023
1024 /* If there are enough neighbors stop here */
1025 if (counter >= 3) {
1026 if (BuildTownHouse(t, tile)) {
1027 _grow_town_result = GROWTH_SUCCEED;
1028 return true;
1029 }
1030 return false;
1031 }
1032 }
1033 return false;
1034 }
1035
1044 static bool GrowTownWithRoad(const Town *t, TileIndex tile, RoadBits rcmd)
1045 {
1046 if (DoCommand(tile, rcmd, t->index, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD).Succeeded()) {
1047 _grow_town_result = GROWTH_SUCCEED;
1048 return true;
1049 }
1050 return false;
1051 }
1052
1063 static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
1064 {
1065 assert(bridge_dir < DIAGDIR_END);
1066
1067 const Slope slope = GetTileSlope(tile);
1068
1069 /* Make sure the direction is compatible with the slope.
1070 * Well we check if the slope has an up bit set in the
1071 * reverse direction. */
1072 if (slope != SLOPE_FLAT && slope & InclinedSlope(bridge_dir)) return false;
1073
1074 /* Assure that the bridge is connectable to the start side */
1075 if (!(GetTownRoadBits(TileAddByDiagDir(tile, ReverseDiagDir(bridge_dir))) & DiagDirToRoadBits(bridge_dir))) return false;
1076
1077 /* We are in the right direction */
1078 uint8 bridge_length = 0; // This value stores the length of the possible bridge
1079 TileIndex bridge_tile = tile; // Used to store the other waterside
1080
1081 const int delta = TileOffsByDiagDir(bridge_dir);
1082
1083 if (slope == SLOPE_FLAT) {
1084 /* Bridges starting on flat tiles are only allowed when crossing rivers. */
1085 do {
1086 if (bridge_length++ >= 4) {
1087 /* Allow to cross rivers, not big lakes. */
1088 return false;
1089 }
1090 bridge_tile += delta;
1091 } while (IsValidTile(bridge_tile) && IsWaterTile(bridge_tile) && !IsSea(bridge_tile));
1092 } else {
1093 do {
1094 if (bridge_length++ >= 11) {
1095 /* Max 11 tile long bridges */
1096 return false;
1097 }
1098 bridge_tile += delta;
1099 } while (IsValidTile(bridge_tile) && IsWaterTile(bridge_tile));
1100 }
1101
1102 /* no water tiles in between? */
1103 if (bridge_length == 1) return false;
1104
1105 for (uint8 times = 0; times <= 22; times++) {
1106 byte bridge_type = RandomRange(MAX_BRIDGES - 1);
1107
1108 /* Can we actually build the bridge? */
1109 if (DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)), CMD_BUILD_BRIDGE).Succeeded()) {
1110 DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, DC_EXEC | CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)), CMD_BUILD_BRIDGE);
1111 _grow_town_result = GROWTH_SUCCEED;
1112 return true;
1113 }
1114 }
1115 /* Quit if it selecting an appropriate bridge type fails a large number of times. */
1116 return false;
1117 }
1118
1136 static void GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1)
1137 {
1138 RoadBits rcmd = ROAD_NONE; // RoadBits for the road construction command
1139 TileIndex tile = *tile_ptr; // The main tile on which we base our growth
1140
1141 assert(tile < MapSize());
1142
1143 if (cur_rb == ROAD_NONE) {
1144 /* Tile has no road. First reset the status counter
1145 * to say that this is the last iteration. */
1146 _grow_town_result = GROWTH_SEARCH_STOPPED;
1147
1148 if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
1149 if (!_settings_game.economy.allow_town_level_crossings && IsTileType(tile, MP_RAILWAY)) return;
1150
1151 /* Remove hills etc */
1152 if (!_settings_game.construction.build_on_slopes || Chance16(1, 6)) LevelTownLand(tile);
1153
1154 /* Is a road allowed here? */
1155 switch (t1->layout) {
1156 default: NOT_REACHED();
1157
1158 case TL_3X3_GRID:
1159 case TL_2X2_GRID:
1160 rcmd = GetTownRoadGridElement(t1, tile, target_dir);
1161 if (rcmd == ROAD_NONE) return;
1162 break;
1163
1164 case TL_BETTER_ROADS:
1165 case TL_ORIGINAL:
1166 if (!IsRoadAllowedHere(t1, tile, target_dir)) return;
1167
1168 DiagDirection source_dir = ReverseDiagDir(target_dir);
1169
1170 if (Chance16(1, 4)) {
1171 /* Randomize a new target dir */
1172 do target_dir = RandomDiagDir(); while (target_dir == source_dir);
1173 }
1174
1175 if (!IsRoadAllowedHere(t1, TileAddByDiagDir(tile, target_dir), target_dir)) {
1176 /* A road is not allowed to continue the randomized road,
1177 * return if the road we're trying to build is curved. */
1178 if (target_dir != ReverseDiagDir(source_dir)) return;
1179
1180 /* Return if neither side of the new road is a house */
1181 if (!IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90RIGHT)), MP_HOUSE) &&
1182 !IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90LEFT)), MP_HOUSE)) {
1183 return;
1184 }
1185
1186 /* That means that the road is only allowed if there is a house
1187 * at any side of the new road. */
1188 }
1189
1190 rcmd = DiagDirToRoadBits(target_dir) | DiagDirToRoadBits(source_dir);
1191 break;
1192 }
1193
1194 } else if (target_dir < DIAGDIR_END && !(cur_rb & DiagDirToRoadBits(ReverseDiagDir(target_dir)))) {
1195 /* Continue building on a partial road.
1196 * Should be always OK, so we only generate
1197 * the fitting RoadBits */
1198 _grow_town_result = GROWTH_SEARCH_STOPPED;
1199
1200 if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
1201
1202 switch (t1->layout) {
1203 default: NOT_REACHED();
1204
1205 case TL_3X3_GRID:
1206 case TL_2X2_GRID:
1207 rcmd = GetTownRoadGridElement(t1, tile, target_dir);
1208 break;
1209
1210 case TL_BETTER_ROADS:
1211 case TL_ORIGINAL:
1212 rcmd = DiagDirToRoadBits(ReverseDiagDir(target_dir));
1213 break;
1214 }
1215 } else {
1216 bool allow_house = true; // Value which decides if we want to construct a house
1217
1218 /* Reached a tunnel/bridge? Then continue at the other side of it, unless
1219 * it is the starting tile. Half the time, we stay on this side then.*/
1220 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1221 if (GetTunnelBridgeTransportType(tile) == TRANSPORT_ROAD && (target_dir != DIAGDIR_END || Chance16(1, 2))) {
1222 *tile_ptr = GetOtherTunnelBridgeEnd(tile);
1223 }
1224 return;
1225 }
1226
1227 /* Possibly extend the road in a direction.
1228 * Randomize a direction and if it has a road, bail out. */
1229 target_dir = RandomDiagDir();
1230 if (cur_rb & DiagDirToRoadBits(target_dir)) return;
1231
1232 /* This is the tile we will reach if we extend to this direction. */
1233 TileIndex house_tile = TileAddByDiagDir(tile, target_dir); // position of a possible house
1234
1235 /* Don't walk into water. */
1236 if (HasTileWaterGround(house_tile)) return;
1237
1238 if (!IsValidTile(house_tile)) return;
1239
1240 if (_settings_game.economy.allow_town_roads || _generating_world) {
1241 switch (t1->layout) {
1242 default: NOT_REACHED();
1243
1244 case TL_3X3_GRID: // Use 2x2 grid afterwards!
1245 GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
1246 /* FALL THROUGH */
1247
1248 case TL_2X2_GRID:
1249 rcmd = GetTownRoadGridElement(t1, house_tile, target_dir);
1250 allow_house = (rcmd == ROAD_NONE);
1251 break;
1252
1253 case TL_BETTER_ROADS: // Use original afterwards!
1254 GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
1255 /* FALL THROUGH */
1256
1257 case TL_ORIGINAL:
1258 /* Allow a house at the edge. 60% chance or
1259 * always ok if no road allowed. */
1260 rcmd = DiagDirToRoadBits(target_dir);
1261 allow_house = (!IsRoadAllowedHere(t1, house_tile, target_dir) || Chance16(6, 10));
1262 break;
1263 }
1264 }
1265
1266 if (allow_house) {
1267 /* Build a house, but not if there already is a house there. */
1268 if (!IsTileType(house_tile, MP_HOUSE)) {
1269 /* Level the land if possible */
1270 if (Chance16(1, 6)) LevelTownLand(house_tile);
1271
1272 /* And build a house.
1273 * Set result to -1 if we managed to build it. */
1274 if (BuildTownHouse(t1, house_tile)) {
1275 _grow_town_result = GROWTH_SUCCEED;
1276 }
1277 }
1278 return;
1279 }
1280
1281 _grow_town_result = GROWTH_SEARCH_STOPPED;
1282 }
1283
1284 /* Return if a water tile */
1285 if (HasTileWaterGround(tile)) return;
1286
1287 /* Make the roads look nicer */
1288 rcmd = CleanUpRoadBits(tile, rcmd);
1289 if (rcmd == ROAD_NONE) return;
1290
1291 /* Only use the target direction for bridges to ensure they're connected.
1292 * The target_dir is as computed previously according to town layout, so
1293 * it will match it perfectly. */
1294 if (GrowTownWithBridge(t1, tile, target_dir)) return;
1295
1296 GrowTownWithRoad(t1, tile, rcmd);
1297 }
1298
1305 static int GrowTownAtRoad(Town *t, TileIndex tile)
1306 {
1307 /* Special case.
1308 * @see GrowTownInTile Check the else if
1309 */
1310 DiagDirection target_dir = DIAGDIR_END; // The direction in which we want to extend the town
1311
1312 assert(tile < MapSize());
1313
1314 /* Number of times to search.
1315 * Better roads, 2X2 and 3X3 grid grow quite fast so we give
1316 * them a little handicap. */
1317 switch (t->layout) {
1318 case TL_BETTER_ROADS:
1319 _grow_town_result = 10 + t->cache.num_houses * 2 / 9;
1320 break;
1321
1322 case TL_3X3_GRID:
1323 case TL_2X2_GRID:
1324 _grow_town_result = 10 + t->cache.num_houses * 1 / 9;
1325 break;
1326
1327 default:
1328 _grow_town_result = 10 + t->cache.num_houses * 4 / 9;
1329 break;
1330 }
1331
1332 do {
1333 RoadBits cur_rb = GetTownRoadBits(tile); // The RoadBits of the current tile
1334
1335 /* Try to grow the town from this point */
1336 GrowTownInTile(&tile, cur_rb, target_dir, t);
1337
1338 /* Exclude the source position from the bitmask
1339 * and return if no more road blocks available */
1340 if (IsValidDiagDirection(target_dir)) cur_rb &= ~DiagDirToRoadBits(ReverseDiagDir(target_dir));
1341 if (cur_rb == ROAD_NONE) {
1342 return _grow_town_result;
1343 }
1344
1345 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1346 /* Only build in the direction away from the tunnel or bridge. */
1347 target_dir = ReverseDiagDir(GetTunnelBridgeDirection(tile));
1348 } else {
1349 /* Select a random bit from the blockmask, walk a step
1350 * and continue the search from there. */
1351 do target_dir = RandomDiagDir(); while (!(cur_rb & DiagDirToRoadBits(target_dir)));
1352 }
1353 tile = TileAddByDiagDir(tile, target_dir);
1354
1355 if (IsTileType(tile, MP_ROAD) && !IsRoadDepot(tile) && HasTileRoadType(tile, ROADTYPE_ROAD)) {
1356 /* Don't allow building over roads of other cities */
1357 if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN) && Town::GetByTile(tile) != t) {
1358 _grow_town_result = GROWTH_SUCCEED;
1359 } else if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_NONE) && _game_mode == GM_EDITOR) {
1360 /* If we are in the SE, and this road-piece has no town owner yet, it just found an
1361 * owner :) (happy happy happy road now) */
1362 SetRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN);
1363 SetTownIndex(tile, t->index);
1364 }
1365 }
1366
1367 /* Max number of times is checked. */
1368 } while (--_grow_town_result >= 0);
1369
1370 return (_grow_town_result == -2);
1371 }
1372
1380 static RoadBits GenRandomRoadBits()
1381 {
1382 uint32 r = Random();
1383 uint a = GB(r, 0, 2);
1384 uint b = GB(r, 8, 2);
1385 if (a == b) b ^= 2;
1386 return (RoadBits)((ROAD_NW << a) + (ROAD_NW << b));
1387 }
1388
1394 static bool GrowTown(Town *t)
1395 {
1396 static const TileIndexDiffC _town_coord_mod[] = {
1397 {-1, 0},
1398 { 1, 1},
1399 { 1, -1},
1400 {-1, -1},
1401 {-1, 0},
1402 { 0, 2},
1403 { 2, 0},
1404 { 0, -2},
1405 {-1, -1},
1406 {-2, 2},
1407 { 2, 2},
1408 { 2, -2},
1409 { 0, 0}
1410 };
1411
1412 /* Current "company" is a town */
1413 Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
1414
1415 TileIndex tile = t->xy; // The tile we are working with ATM
1416
1417 /* Find a road that we can base the construction on. */
1418 const TileIndexDiffC *ptr;
1419 for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
1420 if (GetTownRoadBits(tile) != ROAD_NONE) {
1421 int r = GrowTownAtRoad(t, tile);
1422 cur_company.Restore();
1423 return r != 0;
1424 }
1425 tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
1426 }
1427
1428 /* No road available, try to build a random road block by
1429 * clearing some land and then building a road there. */
1430 if (_settings_game.economy.allow_town_roads || _generating_world) {
1431 tile = t->xy;
1432 for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
1433 /* Only work with plain land that not already has a house */
1434 if (!IsTileType(tile, MP_HOUSE) && IsTileFlat(tile)) {
1435 if (DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded()) {
1436 DoCommand(tile, GenRandomRoadBits(), t->index, DC_EXEC | DC_AUTO, CMD_BUILD_ROAD);
1437 cur_company.Restore();
1438 return true;
1439 }
1440 }
1441 tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
1442 }
1443 }
1444
1445 cur_company.Restore();
1446 return false;
1447 }
1448
1449 void UpdateTownRadius(Town *t)
1450 {
1451 static const uint32 _town_squared_town_zone_radius_data[23][5] = {
1452 { 4, 0, 0, 0, 0}, // 0
1453 { 16, 0, 0, 0, 0},
1454 { 25, 0, 0, 0, 0},
1455 { 36, 0, 0, 0, 0},
1456 { 49, 0, 4, 0, 0},
1457 { 64, 0, 4, 0, 0}, // 20
1458 { 64, 0, 9, 0, 1},
1459 { 64, 0, 9, 0, 4},
1460 { 64, 0, 16, 0, 4},
1461 { 81, 0, 16, 0, 4},
1462 { 81, 0, 16, 0, 4}, // 40
1463 { 81, 0, 25, 0, 9},
1464 { 81, 36, 25, 0, 9},
1465 { 81, 36, 25, 16, 9},
1466 { 81, 49, 0, 25, 9},
1467 { 81, 64, 0, 25, 9}, // 60
1468 { 81, 64, 0, 36, 9},
1469 { 81, 64, 0, 36, 16},
1470 {100, 81, 0, 49, 16},
1471 {100, 81, 0, 49, 25},
1472 {121, 81, 0, 49, 25}, // 80
1473 {121, 81, 0, 49, 25},
1474 {121, 81, 0, 49, 36}, // 88
1475 };
1476
1477 if (t->cache.num_houses < 92) {
1478 memcpy(t->cache.squared_town_zone_radius, _town_squared_town_zone_radius_data[t->cache.num_houses / 4], sizeof(t->cache.squared_town_zone_radius));
1479 } else {
1480 int mass = t->cache.num_houses / 8;
1481 /* Actually we are proportional to sqrt() but that's right because we are covering an area.
1482 * The offsets are to make sure the radii do not decrease in size when going from the table
1483 * to the calculated value.*/
1484 t->cache.squared_town_zone_radius[0] = mass * 15 - 40;
1485 t->cache.squared_town_zone_radius[1] = mass * 9 - 15;
1486 t->cache.squared_town_zone_radius[2] = 0;
1487 t->cache.squared_town_zone_radius[3] = mass * 5 - 5;
1488 t->cache.squared_town_zone_radius[4] = mass * 3 + 5;
1489 }
1490 }
1491
1492 void UpdateTownMaxPass(Town *t)
1493 {
1494 t->supplied[CT_PASSENGERS].old_max = t->cache.population >> 3;
1495 t->supplied[CT_MAIL].old_max = t->cache.population >> 4;
1496 }
1497
1509 static void DoCreateTown(Town *t, TileIndex tile, uint32 townnameparts, TownSize size, bool city, TownLayout layout, bool manual)
1510 {
1511 t->xy = tile;
1512 t->cache.num_houses = 0;
1513 t->time_until_rebuild = 10;
1514 UpdateTownRadius(t);
1515 t->flags = 0;
1516 t->cache.population = 0;
1517 t->grow_counter = 0;
1518 t->growth_rate = 250;
1519
1520 /* Set the default cargo requirement for town growth */
1521 switch (_settings_game.game_creation.landscape) {
1522 case LT_ARCTIC:
1523 if (FindFirstCargoWithTownEffect(TE_FOOD) != NULL) t->goal[TE_FOOD] = TOWN_GROWTH_WINTER;
1524 break;
1525
1526 case LT_TROPIC:
1527 if (FindFirstCargoWithTownEffect(TE_FOOD) != NULL) t->goal[TE_FOOD] = TOWN_GROWTH_DESERT;
1528 if (FindFirstCargoWithTownEffect(TE_WATER) != NULL) t->goal[TE_WATER] = TOWN_GROWTH_DESERT;
1529 break;
1530 }
1531
1532 t->fund_buildings_months = 0;
1533
1534 for (uint i = 0; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
1535
1536 t->have_ratings = 0;
1537 t->exclusivity = INVALID_COMPANY;
1538 t->exclusive_counter = 0;
1539 t->statues = 0;
1540
1541 extern int _nb_orig_names;
1542 if (_settings_game.game_creation.town_name < _nb_orig_names) {
1543 /* Original town name */
1544 t->townnamegrfid = 0;
1545 t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
1546 } else {
1547 /* Newgrf town name */
1548 t->townnamegrfid = GetGRFTownNameId(_settings_game.game_creation.town_name - _nb_orig_names);
1549 t->townnametype = GetGRFTownNameType(_settings_game.game_creation.town_name - _nb_orig_names);
1550 }
1551 t->townnameparts = townnameparts;
1552
1553 t->UpdateVirtCoord();
1554 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
1555
1556 t->InitializeLayout(layout);
1557
1558 t->larger_town = city;
1559
1560 int x = (int)size * 16 + 3;
1561 if (size == TSZ_RANDOM) x = (Random() & 0xF) + 8;
1562 /* Don't create huge cities when founding town in-game */
1563 if (city && (!manual || _game_mode == GM_EDITOR)) x *= _settings_game.economy.initial_city_size;
1564
1565 t->cache.num_houses += x;
1566 UpdateTownRadius(t);
1567
1568 int i = x * 4;
1569 do {
1570 GrowTown(t);
1571 } while (--i);
1572
1573 t->cache.num_houses -= x;
1574 UpdateTownRadius(t);
1575 UpdateTownMaxPass(t);
1576 UpdateAirportsNoise();
1577 }
1578
1584 static CommandCost TownCanBePlacedHere(TileIndex tile)
1585 {
1586 /* Check if too close to the edge of map */
1587 if (DistanceFromEdge(tile) < 12) {
1588 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP_SUB);
1589 }
1590
1591 /* Check distance to all other towns. */
1592 if (IsCloseToTown(tile, 20)) {
1593 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_TOWN);
1594 }
1595
1596 /* Can only build on clear flat areas, possibly with trees. */
1597 if ((!IsTileType(tile, MP_CLEAR) && !IsTileType(tile, MP_TREES)) || !IsTileFlat(tile)) {
1598 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
1599 }
1600
1601 return CommandCost(EXPENSES_OTHER);
1602 }
1603
1609 static bool IsUniqueTownName(const char *name)
1610 {
1611 const Town *t;
1612
1613 FOR_ALL_TOWNS(t) {
1614 if (t->name != NULL && strcmp(t->name, name) == 0) return false;
1615 }
1616
1617 return true;
1618 }
1619
1632 CommandCost CmdFoundTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1633 {
1634 TownSize size = Extract<TownSize, 0, 2>(p1);
1635 bool city = HasBit(p1, 2);
1636 TownLayout layout = Extract<TownLayout, 3, 3>(p1);
1637 TownNameParams par(_settings_game.game_creation.town_name);
1638 bool random = HasBit(p1, 6);
1639 uint32 townnameparts = p2;
1640
1641 if (size >= TSZ_END) return CMD_ERROR;
1642 if (layout >= NUM_TLS) return CMD_ERROR;
1643
1644 /* Some things are allowed only in the scenario editor and for game scripts. */
1645 if (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY) {
1646 if (_settings_game.economy.found_town == TF_FORBIDDEN) return CMD_ERROR;
1647 if (size == TSZ_LARGE) return CMD_ERROR;
1648 if (random) return CMD_ERROR;
1649 if (_settings_game.economy.found_town != TF_CUSTOM_LAYOUT && layout != _settings_game.economy.town_layout) {
1650 return CMD_ERROR;
1651 }
1652 } else if (_current_company == OWNER_DEITY && random) {
1653 /* Random parameter is not allowed for Game Scripts. */
1654 return CMD_ERROR;
1655 }
1656
1657 if (StrEmpty(text)) {
1658 /* If supplied name is empty, townnameparts has to generate unique automatic name */
1659 if (!VerifyTownName(townnameparts, &par)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1660 } else {
1661 /* If name is not empty, it has to be unique custom name */
1662 if (Utf8StringLength(text) >= MAX_LENGTH_TOWN_NAME_CHARS) return CMD_ERROR;
1663 if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1664 }
1665
1666 /* Allocate town struct */
1667 if (!Town::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_TOWNS);
1668
1669 if (!random) {
1670 CommandCost ret = TownCanBePlacedHere(tile);
1671 if (ret.Failed()) return ret;
1672 }
1673
1674 static const byte price_mult[][TSZ_RANDOM + 1] = {{ 15, 25, 40, 25 }, { 20, 35, 55, 35 }};
1675 /* multidimensional arrays have to have defined length of non-first dimension */
1676 assert_compile(lengthof(price_mult[0]) == 4);
1677
1678 CommandCost cost(EXPENSES_OTHER, _price[PR_BUILD_TOWN]);
1679 byte mult = price_mult[city][size];
1680
1681 cost.MultiplyCost(mult);
1682
1683 /* Create the town */
1684 if (flags & DC_EXEC) {
1685 if (cost.GetCost() > GetAvailableMoneyForCommand()) {
1686 _additional_cash_required = cost.GetCost();
1687 return CommandCost(EXPENSES_OTHER);
1688 }
1689
1690 Backup<bool> old_generating_world(_generating_world, true, FILE_LINE);
1691 UpdateNearestTownForRoadTiles(true);
1692 Town *t;
1693 if (random) {
1694 t = CreateRandomTown(20, townnameparts, size, city, layout);
1695 if (t == NULL) {
1696 cost = CommandCost(STR_ERROR_NO_SPACE_FOR_TOWN);
1697 } else {
1698 _new_town_id = t->index;
1699 }
1700 } else {
1701 t = new Town(tile);
1702 DoCreateTown(t, tile, townnameparts, size, city, layout, true);
1703 }
1704 UpdateNearestTownForRoadTiles(false);
1705 old_generating_world.Restore();
1706
1707 if (t != NULL && !StrEmpty(text)) {
1708 t->name = stredup(text);
1709 t->UpdateVirtCoord();
1710 }
1711
1712 if (_game_mode != GM_EDITOR) {
1713 /* 't' can't be NULL since 'random' is false outside scenedit */
1714 assert(!random);
1715 char company_name[MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH];
1716 SetDParam(0, _current_company);
1717 GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
1718
1719 char *cn = stredup(company_name);
1720 SetDParamStr(0, cn);
1721 SetDParam(1, t->index);
1722
1723 AddTileNewsItem(STR_NEWS_NEW_TOWN, NT_INDUSTRY_OPEN, tile, cn);
1724 AI::BroadcastNewEvent(new ScriptEventTownFounded(t->index));
1725 Game::NewEvent(new ScriptEventTownFounded(t->index));
1726 }
1727 }
1728 return cost;
1729 }
1730
1740 static TileIndex AlignTileToGrid(TileIndex tile, TownLayout layout)
1741 {
1742 switch (layout) {
1743 case TL_2X2_GRID: return TileXY(TileX(tile) - TileX(tile) % 3, TileY(tile) - TileY(tile) % 3);
1744 case TL_3X3_GRID: return TileXY(TileX(tile) & ~3, TileY(tile) & ~3);
1745 default: return tile;
1746 }
1747 }
1748
1758 static bool IsTileAlignedToGrid(TileIndex tile, TownLayout layout)
1759 {
1760 switch (layout) {
1761 case TL_2X2_GRID: return TileX(tile) % 3 == 0 && TileY(tile) % 3 == 0;
1762 case TL_3X3_GRID: return TileX(tile) % 4 == 0 && TileY(tile) % 4 == 0;
1763 default: return true;
1764 }
1765 }
1766
1770 struct SpotData {
1771 TileIndex tile;
1772 uint max_dist;
1773 TownLayout layout;
1774 };
1775
1792 static bool FindFurthestFromWater(TileIndex tile, void *user_data)
1793 {
1794 SpotData *sp = (SpotData*)user_data;
1795 uint dist = GetClosestWaterDistance(tile, true);
1796
1797 if (IsTileType(tile, MP_CLEAR) &&
1798 IsTileFlat(tile) &&
1799 IsTileAlignedToGrid(tile, sp->layout) &&
1800 dist > sp->max_dist) {
1801 sp->tile = tile;
1802 sp->max_dist = dist;
1803 }
1804
1805 return false;
1806 }
1807
1814 static bool FindNearestEmptyLand(TileIndex tile, void *user_data)
1815 {
1816 return IsTileType(tile, MP_CLEAR);
1817 }
1818
1831 static TileIndex FindNearestGoodCoastalTownSpot(TileIndex tile, TownLayout layout)
1832 {
1833 SpotData sp = { INVALID_TILE, 0, layout };
1834
1835 TileIndex coast = tile;
1836 if (CircularTileSearch(&coast, 40, FindNearestEmptyLand, NULL)) {
1837 CircularTileSearch(&coast, 10, FindFurthestFromWater, &sp);
1838 return sp.tile;
1839 }
1840
1841 /* if we get here just give up */
1842 return INVALID_TILE;
1843 }
1844
1845 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout)
1846 {
1847 assert(_game_mode == GM_EDITOR || _generating_world); // These are the preconditions for CMD_DELETE_TOWN
1848
1849 if (!Town::CanAllocateItem()) return NULL;
1850
1851 do {
1852 /* Generate a tile index not too close from the edge */
1853 TileIndex tile = AlignTileToGrid(RandomTile(), layout);
1854
1855 /* if we tried to place the town on water, slide it over onto
1856 * the nearest likely-looking spot */
1857 if (IsTileType(tile, MP_WATER)) {
1858 tile = FindNearestGoodCoastalTownSpot(tile, layout);
1859 if (tile == INVALID_TILE) continue;
1860 }
1861
1862 /* Make sure town can be placed here */
1863 if (TownCanBePlacedHere(tile).Failed()) continue;
1864
1865 /* Allocate a town struct */
1866 Town *t = new Town(tile);
1867
1868 DoCreateTown(t, tile, townnameparts, size, city, layout, false);
1869
1870 /* if the population is still 0 at the point, then the
1871 * placement is so bad it couldn't grow at all */
1872 if (t->cache.population > 0) return t;
1873
1874 Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
1875 CommandCost rc = DoCommand(t->xy, t->index, 0, DC_EXEC, CMD_DELETE_TOWN);
1876 cur_company.Restore();
1877 assert(rc.Succeeded());
1878
1879 /* We already know that we can allocate a single town when
1880 * entering this function. However, we create and delete
1881 * a town which "resets" the allocation checks. As such we
1882 * need to check again when assertions are enabled. */
1883 assert(Town::CanAllocateItem());
1884 } while (--attempts != 0);
1885
1886 return NULL;
1887 }
1888
1889 static const byte _num_initial_towns[4] = {5, 11, 23, 46}; // very low, low, normal, high
1890
1898 bool GenerateTowns(TownLayout layout)
1899 {
1900 uint current_number = 0;
1901 uint difficulty = (_game_mode != GM_EDITOR) ? _settings_game.difficulty.number_towns : 0;
1902 uint total = (difficulty == (uint)CUSTOM_TOWN_NUMBER_DIFFICULTY) ? _settings_game.game_creation.custom_town_number : ScaleByMapSize(_num_initial_towns[difficulty] + (Random() & 7));
1903 total = min(TownPool::MAX_SIZE, total);
1904 uint32 townnameparts;
1905 TownNames town_names;
1906
1907 SetGeneratingWorldProgress(GWP_TOWN, total);
1908
1909 /* First attempt will be made at creating the suggested number of towns.
1910 * Note that this is really a suggested value, not a required one.
1911 * We would not like the system to lock up just because the user wanted 100 cities on a 64*64 map, would we? */
1912 do {
1913 bool city = (_settings_game.economy.larger_towns != 0 && Chance16(1, _settings_game.economy.larger_towns));
1914 IncreaseGeneratingWorldProgress(GWP_TOWN);
1915 /* Get a unique name for the town. */
1916 if (!GenerateTownName(&townnameparts, &town_names)) continue;
1917 /* try 20 times to create a random-sized town for the first loop. */
1918 if (CreateRandomTown(20, townnameparts, TSZ_RANDOM, city, layout) != NULL) current_number++; // If creation was successful, raise a flag.
1919 } while (--total);
1920
1921 town_names.clear();
1922
1923 if (current_number != 0) return true;
1924
1925 /* If current_number is still zero at this point, it means that not a single town has been created.
1926 * So give it a last try, but now more aggressive */
1927 if (GenerateTownName(&townnameparts) &&
1928 CreateRandomTown(10000, townnameparts, TSZ_RANDOM, _settings_game.economy.larger_towns != 0, layout) != NULL) {
1929 return true;
1930 }
1931
1932 /* If there are no towns at all and we are generating new game, bail out */
1933 if (Town::GetNumItems() == 0 && _game_mode != GM_EDITOR) {
1934 ShowErrorMessage(STR_ERROR_COULD_NOT_CREATE_TOWN, INVALID_STRING_ID, WL_CRITICAL);
1935 }
1936
1937 return false; // we are still without a town? we failed, simply
1938 }
1939
1940
1947 HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
1948 {
1949 uint dist = DistanceSquare(tile, t->xy);
1950
1951 if (t->fund_buildings_months && dist <= 25) return HZB_TOWN_CENTRE;
1952
1953 HouseZonesBits smallest = HZB_TOWN_EDGE;
1954 for (HouseZonesBits i = HZB_BEGIN; i < HZB_END; i++) {
1955 if (dist < t->cache.squared_town_zone_radius[i]) smallest = i;
1956 }
1957
1958 return smallest;
1959 }
1960
1971 static inline void ClearMakeHouseTile(TileIndex tile, Town *t, byte counter, byte stage, HouseID type, byte random_bits)
1972 {
1973 CommandCost cc = DoCommand(tile, 0, 0, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR);
1974
1975 assert(cc.Succeeded());
1976
1977 IncreaseBuildingCount(t, type);
1978 MakeHouseTile(tile, t->index, counter, stage, type, random_bits);
1979 if (HouseSpec::Get(type)->building_flags & BUILDING_IS_ANIMATED) AddAnimatedTile(tile);
1980
1981 MarkTileDirtyByTile(tile);
1982 }
1983
1984
1995 static void MakeTownHouse(TileIndex t, Town *town, byte counter, byte stage, HouseID type, byte random_bits)
1996 {
1997 BuildingFlags size = HouseSpec::Get(type)->building_flags;
1998
1999 ClearMakeHouseTile(t, town, counter, stage, type, random_bits);
2000 if (size & BUILDING_2_TILES_Y) ClearMakeHouseTile(t + TileDiffXY(0, 1), town, counter, stage, ++type, random_bits);
2001 if (size & BUILDING_2_TILES_X) ClearMakeHouseTile(t + TileDiffXY(1, 0), town, counter, stage, ++type, random_bits);
2002 if (size & BUILDING_HAS_4_TILES) ClearMakeHouseTile(t + TileDiffXY(1, 1), town, counter, stage, ++type, random_bits);
2003 }
2004
2005
2014 static inline bool CanBuildHouseHere(TileIndex tile, TownID town, bool noslope)
2015 {
2016 /* cannot build on these slopes... */
2017 Slope slope = GetTileSlope(tile);
2018 if ((noslope && slope != SLOPE_FLAT) || IsSteepSlope(slope)) return false;
2019
2020 /* building under a bridge? */
2021 if (IsBridgeAbove(tile)) return false;
2022
2023 /* do not try to build over house owned by another town */
2024 if (IsTileType(tile, MP_HOUSE) && GetTownIndex(tile) != town) return false;
2025
2026 /* can we clear the land? */
2027 return DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded();
2028 }
2029
2030
2040 static inline bool CheckBuildHouseSameZ(TileIndex tile, TownID town, int z, bool noslope)
2041 {
2042 if (!CanBuildHouseHere(tile, town, noslope)) return false;
2043
2044 /* if building on slopes is allowed, there will be flattening foundation (to tile max z) */
2045 if (GetTileMaxZ(tile) != z) return false;
2046
2047 return true;
2048 }
2049
2050
2060 static bool CheckFree2x2Area(TileIndex tile, TownID town, int z, bool noslope)
2061 {
2062 /* we need to check this tile too because we can be at different tile now */
2063 if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
2064
2065 for (DiagDirection d = DIAGDIR_SE; d < DIAGDIR_END; d++) {
2066 tile += TileOffsByDiagDir(d);
2067 if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
2068 }
2069
2070 return true;
2071 }
2072
2073
2081 static inline bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile)
2082 {
2083 /* Allow towns everywhere when we don't build roads */
2084 if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
2085
2086 TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
2087
2088 switch (t->layout) {
2089 case TL_2X2_GRID:
2090 if ((grid_pos.x % 3) == 0 || (grid_pos.y % 3) == 0) return false;
2091 break;
2092
2093 case TL_3X3_GRID:
2094 if ((grid_pos.x % 4) == 0 || (grid_pos.y % 4) == 0) return false;
2095 break;
2096
2097 default:
2098 break;
2099 }
2100
2101 return true;
2102 }
2103
2104
2112 static inline bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile)
2113 {
2114 /* Allow towns everywhere when we don't build roads */
2115 if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
2116
2117 /* Compute relative position of tile. (Positive offsets are towards north) */
2118 TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
2119
2120 switch (t->layout) {
2121 case TL_2X2_GRID:
2122 grid_pos.x %= 3;
2123 grid_pos.y %= 3;
2124 if ((grid_pos.x != 2 && grid_pos.x != -1) ||
2125 (grid_pos.y != 2 && grid_pos.y != -1)) return false;
2126 break;
2127
2128 case TL_3X3_GRID:
2129 if ((grid_pos.x & 3) < 2 || (grid_pos.y & 3) < 2) return false;
2130 break;
2131
2132 default:
2133 break;
2134 }
2135
2136 return true;
2137 }
2138
2139
2149 static bool CheckTownBuild2House(TileIndex *tile, Town *t, int maxz, bool noslope, DiagDirection second)
2150 {
2151 /* 'tile' is already checked in BuildTownHouse() - CanBuildHouseHere() and slope test */
2152
2153 TileIndex tile2 = *tile + TileOffsByDiagDir(second);
2154 if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) return true;
2155
2156 tile2 = *tile + TileOffsByDiagDir(ReverseDiagDir(second));
2157 if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) {
2158 *tile = tile2;
2159 return true;
2160 }
2161
2162 return false;
2163 }
2164
2165
2174 static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, int maxz, bool noslope)
2175 {
2176 TileIndex tile2 = *tile;
2177
2178 for (DiagDirection d = DIAGDIR_SE;; d++) { // 'd' goes through DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_END
2179 if (TownLayoutAllows2x2HouseHere(t, tile2) && CheckFree2x2Area(tile2, t->index, maxz, noslope)) {
2180 *tile = tile2;
2181 return true;
2182 }
2183 if (d == DIAGDIR_END) break;
2184 tile2 += TileOffsByDiagDir(ReverseDiagDir(d)); // go clockwise
2185 }
2186
2187 return false;
2188 }
2189
2190
2197 static bool BuildTownHouse(Town *t, TileIndex tile)
2198 {
2199 /* forbidden building here by town layout */
2200 if (!TownLayoutAllowsHouseHere(t, tile)) return false;
2201
2202 /* no house allowed at all, bail out */
2203 if (!CanBuildHouseHere(tile, t->index, false)) return false;
2204
2205 Slope slope = GetTileSlope(tile);
2206 int maxz = GetTileMaxZ(tile);
2207
2208 /* Get the town zone type of the current tile, as well as the climate.
2209 * This will allow to easily compare with the specs of the new house to build */
2210 HouseZonesBits rad = GetTownRadiusGroup(t, tile);
2211
2212 /* Above snow? */
2213 int land = _settings_game.game_creation.landscape;
2214 if (land == LT_ARCTIC && maxz > HighestSnowLine()) land = -1;
2215
2216 uint bitmask = (1 << rad) + (1 << (land + 12));
2217
2218 /* bits 0-4 are used
2219 * bits 11-15 are used
2220 * bits 5-10 are not used. */
2221 HouseID houses[NUM_HOUSES];
2222 uint num = 0;
2223 uint probs[NUM_HOUSES];
2224 uint probability_max = 0;
2225
2226 /* Generate a list of all possible houses that can be built. */
2227 for (uint i = 0; i < NUM_HOUSES; i++) {
2228 const HouseSpec *hs = HouseSpec::Get(i);
2229
2230 /* Verify that the candidate house spec matches the current tile status */
2231 if ((~hs->building_availability & bitmask) != 0 || !hs->enabled || hs->grf_prop.override != INVALID_HOUSE_ID) continue;
2232
2233 /* Don't let these counters overflow. Global counters are 32bit, there will never be that many houses. */
2234 if (hs->class_id != HOUSE_NO_CLASS) {
2235 /* id_count is always <= class_count, so it doesn't need to be checked */
2236 if (t->cache.building_counts.class_count[hs->class_id] == UINT16_MAX) continue;
2237 } else {
2238 /* If the house has no class, check id_count instead */
2239 if (t->cache.building_counts.id_count[i] == UINT16_MAX) continue;
2240 }
2241
2242 /* Without NewHouses, all houses have probability '1' */
2243 uint cur_prob = (_loaded_newgrf_features.has_newhouses ? hs->probability : 1);
2244 probability_max += cur_prob;
2245 probs[num] = cur_prob;
2246 houses[num++] = (HouseID)i;
2247 }
2248
2249 TileIndex baseTile = tile;
2250
2251 while (probability_max > 0) {
2252 /* Building a multitile building can change the location of tile.
2253 * The building would still be built partially on that tile, but
2254 * its northern tile would be elsewhere. However, if the callback
2255 * fails we would be basing further work from the changed tile.
2256 * So a next 1x1 tile building could be built on the wrong tile. */
2257 tile = baseTile;
2258
2259 uint r = RandomRange(probability_max);
2260 uint i;
2261 for (i = 0; i < num; i++) {
2262 if (probs[i] > r) break;
2263 r -= probs[i];
2264 }
2265
2266 HouseID house = houses[i];
2267 probability_max -= probs[i];
2268
2269 /* remove tested house from the set */
2270 num--;
2271 houses[i] = houses[num];
2272 probs[i] = probs[num];
2273
2274 const HouseSpec *hs = HouseSpec::Get(house);
2275
2276 if (_loaded_newgrf_features.has_newhouses && !_generating_world &&
2277 _game_mode != GM_EDITOR && (hs->extra_flags & BUILDING_IS_HISTORICAL) != 0) {
2278 continue;
2279 }
2280
2281 if (_cur_year < hs->min_year || _cur_year > hs->max_year) continue;
2282
2283 /* Special houses that there can be only one of. */
2284 uint oneof = 0;
2285
2286 if (hs->building_flags & BUILDING_IS_CHURCH) {
2287 SetBit(oneof, TOWN_HAS_CHURCH);
2288 } else if (hs->building_flags & BUILDING_IS_STADIUM) {
2289 SetBit(oneof, TOWN_HAS_STADIUM);
2290 }
2291
2292 if (t->flags & oneof) continue;
2293
2294 /* Make sure there is no slope? */
2295 bool noslope = (hs->building_flags & TILE_NOT_SLOPED) != 0;
2296 if (noslope && slope != SLOPE_FLAT) continue;
2297
2298 if (hs->building_flags & TILE_SIZE_2x2) {
2299 if (!CheckTownBuild2x2House(&tile, t, maxz, noslope)) continue;
2300 } else if (hs->building_flags & TILE_SIZE_2x1) {
2301 if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SW)) continue;
2302 } else if (hs->building_flags & TILE_SIZE_1x2) {
2303 if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SE)) continue;
2304 } else {
2305 /* 1x1 house checks are already done */
2306 }
2307
2308 byte random_bits = Random();
2309
2310 if (HasBit(hs->callback_mask, CBM_HOUSE_ALLOW_CONSTRUCTION)) {
2311 uint16 callback_res = GetHouseCallback(CBID_HOUSE_ALLOW_CONSTRUCTION, 0, 0, house, t, tile, true, random_bits);
2312 if (callback_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_ALLOW_CONSTRUCTION, callback_res)) continue;
2313 }
2314
2315 /* build the house */
2316 t->cache.num_houses++;
2317
2318 /* Special houses that there can be only one of. */
2319 t->flags |= oneof;
2320
2321 byte construction_counter = 0;
2322 byte construction_stage = 0;
2323
2324 if (_generating_world || _game_mode == GM_EDITOR) {
2325 uint32 r = Random();
2326
2327 construction_stage = TOWN_HOUSE_COMPLETED;
2328 if (Chance16(1, 7)) construction_stage = GB(r, 0, 2);
2329
2330 if (construction_stage == TOWN_HOUSE_COMPLETED) {
2331 ChangePopulation(t, hs->population);
2332 } else {
2333 construction_counter = GB(r, 2, 2);
2334 }
2335 }
2336
2337 MakeTownHouse(tile, t, construction_counter, construction_stage, house, random_bits);
2338 UpdateTownRadius(t);
2339 UpdateTownCargoes(t, tile);
2340
2341 return true;
2342 }
2343
2344 return false;
2345 }
2346
2353 static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
2354 {
2355 assert(IsTileType(tile, MP_HOUSE));
2356 DecreaseBuildingCount(t, house);
2357 DoClearSquare(tile);
2358 DeleteAnimatedTile(tile);
2359
2360 DeleteNewGRFInspectWindow(GSF_HOUSES, tile);
2361 }
2362
2370 TileIndexDiff GetHouseNorthPart(HouseID &house)
2371 {
2372 if (house >= 3) { // house id 0,1,2 MUST be single tile houses, or this code breaks.
2373 if (HouseSpec::Get(house - 1)->building_flags & TILE_SIZE_2x1) {
2374 house--;
2375 return TileDiffXY(-1, 0);
2376 } else if (HouseSpec::Get(house - 1)->building_flags & BUILDING_2_TILES_Y) {
2377 house--;
2378 return TileDiffXY(0, -1);
2379 } else if (HouseSpec::Get(house - 2)->building_flags & BUILDING_HAS_4_TILES) {
2380 house -= 2;
2381 return TileDiffXY(-1, 0);
2382 } else if (HouseSpec::Get(house - 3)->building_flags & BUILDING_HAS_4_TILES) {
2383 house -= 3;
2384 return TileDiffXY(-1, -1);
2385 }
2386 }
2387 return 0;
2388 }
2389
2390 void ClearTownHouse(Town *t, TileIndex tile)
2391 {
2392 assert(IsTileType(tile, MP_HOUSE));
2393
2394 HouseID house = GetHouseType(tile);
2395
2396 /* need to align the tile to point to the upper left corner of the house */
2397 tile += GetHouseNorthPart(house); // modifies house to the ID of the north tile
2398
2399 const HouseSpec *hs = HouseSpec::Get(house);
2400
2401 /* Remove population from the town if the house is finished. */
2402 if (IsHouseCompleted(tile)) {
2403 ChangePopulation(t, -hs->population);
2404 }
2405
2406 t->cache.num_houses--;
2407
2408 /* Clear flags for houses that only may exist once/town. */
2409 if (hs->building_flags & BUILDING_IS_CHURCH) {
2410 ClrBit(t->flags, TOWN_HAS_CHURCH);
2411 } else if (hs->building_flags & BUILDING_IS_STADIUM) {
2412 ClrBit(t->flags, TOWN_HAS_STADIUM);
2413 }
2414
2415 /* Do the actual clearing of tiles */
2416 uint eflags = hs->building_flags;
2417 DoClearTownHouseHelper(tile, t, house);
2418 if (eflags & BUILDING_2_TILES_Y) DoClearTownHouseHelper(tile + TileDiffXY(0, 1), t, ++house);
2419 if (eflags & BUILDING_2_TILES_X) DoClearTownHouseHelper(tile + TileDiffXY(1, 0), t, ++house);
2420 if (eflags & BUILDING_HAS_4_TILES) DoClearTownHouseHelper(tile + TileDiffXY(1, 1), t, ++house);
2421
2422 UpdateTownRadius(t);
2423
2424 /* Update cargo acceptance. */
2425 UpdateTownCargoes(t, tile);
2426 }
2427
2437 CommandCost CmdRenameTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2438 {
2439 Town *t = Town::GetIfValid(p1);
2440 if (t == NULL) return CMD_ERROR;
2441
2442 bool reset = StrEmpty(text);
2443
2444 if (!reset) {
2445 if (Utf8StringLength(text) >= MAX_LENGTH_TOWN_NAME_CHARS) return CMD_ERROR;
2446 if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
2447 }
2448
2449 if (flags & DC_EXEC) {
2450 free(t->name);
2451 t->name = reset ? NULL : stredup(text);
2452
2453 t->UpdateVirtCoord();
2454 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
2455 UpdateAllStationVirtCoords();
2456 }
2457 return CommandCost();
2458 }
2459
2465 const CargoSpec *FindFirstCargoWithTownEffect(TownEffect effect)
2466 {
2467 const CargoSpec *cs;
2468 FOR_ALL_CARGOSPECS(cs) {
2469 if (cs->town_effect == effect) return cs;
2470 }
2471 return NULL;
2472 }
2473
2474 static void UpdateTownGrowRate(Town *t);
2475
2487 CommandCost CmdTownCargoGoal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2488 {
2489 if (_current_company != OWNER_DEITY) return CMD_ERROR;
2490
2491 TownEffect te = (TownEffect)GB(p1, 16, 8);
2492 if (te < TE_BEGIN || te >= TE_END) return CMD_ERROR;
2493
2494 uint16 index = GB(p1, 0, 16);
2495 Town *t = Town::GetIfValid(index);
2496 if (t == NULL) return CMD_ERROR;
2497
2498 /* Validate if there is a cargo which is the requested TownEffect */
2499 const CargoSpec *cargo = FindFirstCargoWithTownEffect(te);
2500 if (cargo == NULL) return CMD_ERROR;
2501
2502 if (flags & DC_EXEC) {
2503 t->goal[te] = p2;
2504 UpdateTownGrowRate(t);
2505 InvalidateWindowData(WC_TOWN_VIEW, index);
2506 }
2507
2508 return CommandCost();
2509 }
2510
2520 CommandCost CmdTownSetText(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2521 {
2522 if (_current_company != OWNER_DEITY) return CMD_ERROR;
2523 Town *t = Town::GetIfValid(p1);
2524 if (t == NULL) return CMD_ERROR;
2525
2526 if (flags & DC_EXEC) {
2527 free(t->text);
2528 t->text = StrEmpty(text) ? NULL : stredup(text);
2529 InvalidateWindowData(WC_TOWN_VIEW, p1);
2530 }
2531
2532 return CommandCost();
2533 }
2534
2544 CommandCost CmdTownGrowthRate(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2545 {
2546 if (_current_company != OWNER_DEITY) return CMD_ERROR;
2547 if ((p2 & TOWN_GROW_RATE_CUSTOM) != 0 && p2 != TOWN_GROW_RATE_CUSTOM_NONE) return CMD_ERROR;
2548 if (GB(p2, 16, 16) != 0) return CMD_ERROR;
2549
2550 Town *t = Town::GetIfValid(p1);
2551 if (t == NULL) return CMD_ERROR;
2552
2553 if (flags & DC_EXEC) {
2554 if (p2 == 0) {
2555 /* Clear TOWN_GROW_RATE_CUSTOM, UpdateTownGrowRate will determine a proper value */
2556 t->growth_rate = 0;
2557 } else {
2558 uint old_rate = t->growth_rate & ~TOWN_GROW_RATE_CUSTOM;
2559 if (t->grow_counter >= old_rate) {
2560 /* This also catches old_rate == 0 */
2561 t->grow_counter = p2;
2562 } else {
2563 /* Scale grow_counter, so half finished houses stay half finished */
2564 t->grow_counter = t->grow_counter * p2 / old_rate;
2565 }
2566 t->growth_rate = p2 | TOWN_GROW_RATE_CUSTOM;
2567 }
2568 UpdateTownGrowRate(t);
2569 InvalidateWindowData(WC_TOWN_VIEW, p1);
2570 }
2571
2572 return CommandCost();
2573 }
2574
2584 CommandCost CmdExpandTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2585 {
2586 if (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY) return CMD_ERROR;
2587 Town *t = Town::GetIfValid(p1);
2588 if (t == NULL) return CMD_ERROR;
2589
2590 if (flags & DC_EXEC) {
2591 /* The more houses, the faster we grow */
2592 if (p2 == 0) {
2593 uint amount = RandomRange(ClampToU16(t->cache.num_houses / 10)) + 3;
2594 t->cache.num_houses += amount;
2595 UpdateTownRadius(t);
2596
2597 uint n = amount * 10;
2598 do GrowTown(t); while (--n);
2599
2600 t->cache.num_houses -= amount;
2601 } else {
2602 for (; p2 > 0; p2--) {
2603 /* Try several times to grow, as we are really suppose to grow */
2604 for (uint i = 0; i < 25; i++) if (GrowTown(t)) break;
2605 }
2606 }
2607 UpdateTownRadius(t);
2608
2609 UpdateTownMaxPass(t);
2610 }
2611
2612 return CommandCost();
2613 }
2614
2624 CommandCost CmdDeleteTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2625 {
2626 if (_game_mode != GM_EDITOR && !_generating_world) return CMD_ERROR;
2627 Town *t = Town::GetIfValid(p1);
2628 if (t == NULL) return CMD_ERROR;
2629
2630 /* Stations refer to towns. */
2631 const Station *st;
2632 FOR_ALL_STATIONS(st) {
2633 if (st->town == t) {
2634 /* Non-oil rig stations are always a problem. */
2635 if (!(st->facilities & FACIL_AIRPORT) || st->airport.type != AT_OILRIG) return CMD_ERROR;
2636 /* We can only automatically delete oil rigs *if* there's no vehicle on them. */
2637 CommandCost ret = DoCommand(st->airport.tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2638 if (ret.Failed()) return ret;
2639 }
2640 }
2641
2642 /* Depots refer to towns. */
2643 const Depot *d;
2644 FOR_ALL_DEPOTS(d) {
2645 if (d->town == t) return CMD_ERROR;
2646 }
2647
2648 /* Check all tiles for town ownership. */
2649 for (TileIndex tile = 0; tile < MapSize(); ++tile) {
2650 bool try_clear = false;
2651 switch (GetTileType(tile)) {
2652 case MP_ROAD:
2653 try_clear = HasTownOwnedRoad(tile) && GetTownIndex(tile) == t->index;
2654 break;
2655
2656 case MP_TUNNELBRIDGE:
2657 try_clear = IsTileOwner(tile, OWNER_TOWN) && ClosestTownFromTile(tile, UINT_MAX) == t;
2658 break;
2659
2660 case MP_HOUSE:
2661 try_clear = GetTownIndex(tile) == t->index;
2662 break;
2663
2664 case MP_INDUSTRY:
2665 try_clear = Industry::GetByTile(tile)->town == t;
2666 break;
2667
2668 case MP_OBJECT:
2669 if (Town::GetNumItems() == 1) {
2670 /* No towns will be left, remove it! */
2671 try_clear = true;
2672 } else {
2673 Object *o = Object::GetByTile(tile);
2674 if (o->town == t) {
2675 if (o->type == OBJECT_STATUE) {
2676 /* Statue... always remove. */
2677 try_clear = true;
2678 } else {
2679 /* Tell to find a new town. */
2680 if (flags & DC_EXEC) o->town = NULL;
2681 }
2682 }
2683 }
2684 break;
2685
2686 default:
2687 break;
2688 }
2689 if (try_clear) {
2690 CommandCost ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2691 if (ret.Failed()) return ret;
2692 }
2693 }
2694
2695 /* The town destructor will delete the other things related to the town. */
2696 if (flags & DC_EXEC) delete t;
2697
2698 return CommandCost();
2699 }
2700
2705 const byte _town_action_costs[TACT_COUNT] = {
2706 2, 4, 9, 35, 48, 53, 117, 175
2707 };
2708
2709 static CommandCost TownActionAdvertiseSmall(Town *t, DoCommandFlag flags)
2710 {
2711 if (flags & DC_EXEC) {
2712 ModifyStationRatingAround(t->xy, _current_company, 0x40, 10);
2713 }
2714 return CommandCost();
2715 }
2716
2717 static CommandCost TownActionAdvertiseMedium(Town *t, DoCommandFlag flags)
2718 {
2719 if (flags & DC_EXEC) {
2720 ModifyStationRatingAround(t->xy, _current_company, 0x70, 15);
2721 }
2722 return CommandCost();
2723 }
2724
2725 static CommandCost TownActionAdvertiseLarge(Town *t, DoCommandFlag flags)
2726 {
2727 if (flags & DC_EXEC) {
2728 ModifyStationRatingAround(t->xy, _current_company, 0xA0, 20);
2729 }
2730 return CommandCost();
2731 }
2732
2733 static CommandCost TownActionRoadRebuild(Town *t, DoCommandFlag flags)
2734 {
2735 /* Check if the company is allowed to fund new roads. */
2736 if (!_settings_game.economy.fund_roads) return CMD_ERROR;
2737
2738 if (flags & DC_EXEC) {
2739 t->road_build_months = 6;
2740
2741 char company_name[MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH];
2742 SetDParam(0, _current_company);
2743 GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
2744
2745 char *cn = stredup(company_name);
2746 SetDParam(0, t->index);
2747 SetDParamStr(1, cn);
2748
2749 AddNewsItem(STR_NEWS_ROAD_REBUILDING, NT_GENERAL, NF_NORMAL, NR_TOWN, t->index, NR_NONE, UINT32_MAX, cn);
2750 AI::BroadcastNewEvent(new ScriptEventRoadReconstruction((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
2751 Game::NewEvent(new ScriptEventRoadReconstruction((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
2752 }
2753 return CommandCost();
2754 }
2755
2761 static bool TryClearTile(TileIndex tile)
2762 {
2763 Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
2764 CommandCost r = DoCommand(tile, 0, 0, DC_NONE, CMD_LANDSCAPE_CLEAR);
2765 cur_company.Restore();
2766 return r.Succeeded();
2767 }
2768
2770 struct StatueBuildSearchData {
2771 TileIndex best_position;
2772 int tile_count;
2773
2774 StatueBuildSearchData(TileIndex best_pos, int count) : best_position(best_pos), tile_count(count) { }
2775 };
2776
2783 static bool SearchTileForStatue(TileIndex tile, void *user_data)
2784 {
2785 static const int STATUE_NUMBER_INNER_TILES = 25; // Number of tiles int the center of the city, where we try to protect houses.
2786
2787 StatueBuildSearchData *statue_data = (StatueBuildSearchData *)user_data;
2788 statue_data->tile_count++;
2789
2790 /* Statues can be build on slopes, just like houses. Only the steep slopes is a no go. */
2791 if (IsSteepSlope(GetTileSlope(tile))) return false;
2792 /* Don't build statues under bridges. */
2793 if (IsBridgeAbove(tile)) return false;
2794
2795 /* A clear-able open space is always preferred. */
2796 if ((IsTileType(tile, MP_CLEAR) || IsTileType(tile, MP_TREES)) && TryClearTile(tile)) {
2797 statue_data->best_position = tile;
2798 return true;
2799 }
2800
2801 bool house = IsTileType(tile, MP_HOUSE);
2802
2803 /* Searching inside the inner circle. */
2804 if (statue_data->tile_count <= STATUE_NUMBER_INNER_TILES) {
2805 /* Save first house in inner circle. */
2806 if (house && statue_data->best_position == INVALID_TILE && TryClearTile(tile)) {
2807 statue_data->best_position = tile;
2808 }
2809
2810 /* If we have reached the end of the inner circle, and have a saved house, terminate the search. */
2811 return statue_data->tile_count == STATUE_NUMBER_INNER_TILES && statue_data->best_position != INVALID_TILE;
2812 }
2813
2814 /* Searching outside the circle, just pick the first possible spot. */
2815 statue_data->best_position = tile; // Is optimistic, the condition below must also hold.
2816 return house && TryClearTile(tile);
2817 }
2818
2826 static CommandCost TownActionBuildStatue(Town *t, DoCommandFlag flags)
2827 {
2828 if (!Object::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_OBJECTS);
2829
2830 TileIndex tile = t->xy;
2831 StatueBuildSearchData statue_data(INVALID_TILE, 0);
2832 if (!CircularTileSearch(&tile, 9, SearchTileForStatue, &statue_data)) return_cmd_error(STR_ERROR_STATUE_NO_SUITABLE_PLACE);
2833
2834 if (flags & DC_EXEC) {
2835 Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
2836 DoCommand(statue_data.best_position, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
2837 cur_company.Restore();
2838 BuildObject(OBJECT_STATUE, statue_data.best_position, _current_company, t);
2839 SetBit(t->statues, _current_company); // Once found and built, "inform" the Town.
2840 MarkTileDirtyByTile(statue_data.best_position);
2841 }
2842 return CommandCost();
2843 }
2844
2845 static CommandCost TownActionFundBuildings(Town *t, DoCommandFlag flags)
2846 {
2847 /* Check if it's allowed to buy the rights */
2848 if (!_settings_game.economy.fund_buildings) return CMD_ERROR;
2849
2850 if (flags & DC_EXEC) {
2851 /* Build next tick */
2852 t->grow_counter = 1;
2853 /* And grow for 3 months */
2854 t->fund_buildings_months = 3;
2855
2856 /* Enable growth (also checking GameScript's opinion) */
2857 UpdateTownGrowRate(t);
2858
2859 SetWindowDirty(WC_TOWN_VIEW, t->index);
2860 }
2861 return CommandCost();
2862 }
2863
2864 static CommandCost TownActionBuyRights(Town *t, DoCommandFlag flags)
2865 {
2866 /* Check if it's allowed to buy the rights */
2867 if (!_settings_game.economy.exclusive_rights) return CMD_ERROR;
2868
2869 if (flags & DC_EXEC) {
2870 t->exclusive_counter = 12;
2871 t->exclusivity = _current_company;
2872
2873 ModifyStationRatingAround(t->xy, _current_company, 130, 17);
2874
2875 SetWindowClassesDirty(WC_STATION_VIEW);
2876
2877 /* Spawn news message */
2878 CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
2879 cni->FillData(Company::Get(_current_company));
2880 SetDParam(0, STR_NEWS_EXCLUSIVE_RIGHTS_TITLE);
2881 SetDParam(1, STR_NEWS_EXCLUSIVE_RIGHTS_DESCRIPTION);
2882 SetDParam(2, t->index);
2883 SetDParamStr(3, cni->company_name);
2884 AddNewsItem(STR_MESSAGE_NEWS_FORMAT, NT_GENERAL, NF_COMPANY, NR_TOWN, t->index, NR_NONE, UINT32_MAX, cni);
2885 AI::BroadcastNewEvent(new ScriptEventExclusiveTransportRights((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
2886 Game::NewEvent(new ScriptEventExclusiveTransportRights((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
2887 }
2888 return CommandCost();
2889 }
2890
2891 static CommandCost TownActionBribe(Town *t, DoCommandFlag flags)
2892 {
2893 if (flags & DC_EXEC) {
2894 if (Chance16(1, 14)) {
2895 /* set as unwanted for 6 months */
2896 t->unwanted[_current_company] = 6;
2897
2898 /* set all close by station ratings to 0 */
2899 Station *st;
2900 FOR_ALL_STATIONS(st) {
2901 if (st->town == t && st->owner == _current_company) {
2902 for (CargoID i = 0; i < NUM_CARGO; i++) st->goods[i].rating = 0;
2903 }
2904 }
2905
2906 /* only show error message to the executing player. All errors are handled command.c
2907 * but this is special, because it can only 'fail' on a DC_EXEC */
2908 if (IsLocalCompany()) ShowErrorMessage(STR_ERROR_BRIBE_FAILED, INVALID_STRING_ID, WL_INFO);
2909
2910 /* decrease by a lot!
2911 * ChangeTownRating is only for stuff in demolishing. Bribe failure should
2912 * be independent of any cheat settings
2913 */
2914 if (t->ratings[_current_company] > RATING_BRIBE_DOWN_TO) {
2915 t->ratings[_current_company] = RATING_BRIBE_DOWN_TO;
2916 SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
2917 }
2918 } else {
2919 ChangeTownRating(t, RATING_BRIBE_UP_STEP, RATING_BRIBE_MAXIMUM, DC_EXEC);
2920 }
2921 }
2922 return CommandCost();
2923 }
2924
2925 typedef CommandCost TownActionProc(Town *t, DoCommandFlag flags);
2926 static TownActionProc * const _town_action_proc[] = {
2927 TownActionAdvertiseSmall,
2928 TownActionAdvertiseMedium,
2929 TownActionAdvertiseLarge,
2930 TownActionRoadRebuild,
2931 TownActionBuildStatue,
2932 TownActionFundBuildings,
2933 TownActionBuyRights,
2934 TownActionBribe
2935 };
2936
2944 uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t)
2945 {
2946 int num = 0;
2947 TownActions buttons = TACT_NONE;
2948
2949 /* Spectators and unwanted have no options */
2950 if (cid != COMPANY_SPECTATOR && !(_settings_game.economy.bribe && t->unwanted[cid])) {
2951
2952 /* Things worth more than this are not shown */
2953 Money avail = Company::Get(cid)->money + _price[PR_STATION_VALUE] * 200;
2954
2955 /* Check the action bits for validity and
2956 * if they are valid add them */
2957 for (uint i = 0; i != lengthof(_town_action_costs); i++) {
2958 const TownActions cur = (TownActions)(1 << i);
2959
2960 /* Is the company not able to bribe ? */
2961 if (cur == TACT_BRIBE && (!_settings_game.economy.bribe || t->ratings[cid] >= RATING_BRIBE_MAXIMUM)) continue;
2962
2963 /* Is the company not able to buy exclusive rights ? */
2964 if (cur == TACT_BUY_RIGHTS && !_settings_game.economy.exclusive_rights) continue;
2965
2966 /* Is the company not able to fund buildings ? */
2967 if (cur == TACT_FUND_BUILDINGS && !_settings_game.economy.fund_buildings) continue;
2968
2969 /* Is the company not able to fund local road reconstruction? */
2970 if (cur == TACT_ROAD_REBUILD && !_settings_game.economy.fund_roads) continue;
2971
2972 /* Is the company not able to build a statue ? */
2973 if (cur == TACT_BUILD_STATUE && HasBit(t->statues, cid)) continue;
2974
2975 if (avail >= _town_action_costs[i] * _price[PR_TOWN_ACTION] >> 8) {
2976 buttons |= cur;
2977 num++;
2978 }
2979 }
2980 }
2981
2982 if (nump != NULL) *nump = num;
2983 return buttons;
2984 }
2985
2997 CommandCost CmdDoTownAction(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2998 {
2999 Town *t = Town::GetIfValid(p1);
3000 if (t == NULL || p2 >= lengthof(_town_action_proc)) return CMD_ERROR;
3001
3002 if (!HasBit(GetMaskOfTownActions(NULL, _current_company, t), p2)) return CMD_ERROR;
3003
3004 CommandCost cost(EXPENSES_OTHER, _price[PR_TOWN_ACTION] * _town_action_costs[p2] >> 8);
3005
3006 CommandCost ret = _town_action_proc[p2](t, flags);
3007 if (ret.Failed()) return ret;
3008
3009 if (flags & DC_EXEC) {
3010 SetWindowDirty(WC_TOWN_AUTHORITY, p1);
3011 }
3012
3013 return cost;
3014 }
3015
3016 static void UpdateTownRating(Town *t)
3017 {
3018 /* Increase company ratings if they're low */
3019 const Company *c;
3020 FOR_ALL_COMPANIES(c) {
3021 if (t->ratings[c->index] < RATING_GROWTH_MAXIMUM) {
3022 t->ratings[c->index] = min((int)RATING_GROWTH_MAXIMUM, t->ratings[c->index] + RATING_GROWTH_UP_STEP);
3023 }
3024 }
3025
3026 const Station *st;
3027 FOR_ALL_STATIONS(st) {
3028 if (DistanceSquare(st->xy, t->xy) <= t->cache.squared_town_zone_radius[0]) {
3029 if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
3030 if (Company::IsValidID(st->owner)) {
3031 int new_rating = t->ratings[st->owner] + RATING_STATION_UP_STEP;
3032 t->ratings[st->owner] = min(new_rating, INT16_MAX); // do not let it overflow
3033 }
3034 } else {
3035 if (Company::IsValidID(st->owner)) {
3036 int new_rating = t->ratings[st->owner] + RATING_STATION_DOWN_STEP;
3037 t->ratings[st->owner] = max(new_rating, INT16_MIN);
3038 }
3039 }
3040 }
3041 }
3042
3043 /* clamp all ratings to valid values */
3044 for (uint i = 0; i < MAX_COMPANIES; i++) {
3045 t->ratings[i] = Clamp(t->ratings[i], RATING_MINIMUM, RATING_MAXIMUM);
3046 }
3047
3048 SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
3049 }
3050
3051 static void UpdateTownGrowRate(Town *t)
3052 {
3053 ClrBit(t->flags, TOWN_IS_GROWING);
3054 SetWindowDirty(WC_TOWN_VIEW, t->index);
3055
3056 if (_settings_game.economy.town_growth_rate == 0 && t->fund_buildings_months == 0) return;
3057
3058 if (t->fund_buildings_months == 0) {
3059 /* Check if all goals are reached for this town to grow (given we are not funding it) */
3060 for (int i = TE_BEGIN; i < TE_END; i++) {
3061 switch (t->goal[i]) {
3062 case TOWN_GROWTH_WINTER:
3063 if (TileHeight(t->xy) >= GetSnowLine() && t->received[i].old_act == 0 && t->cache.population > 90) return;
3064 break;
3065 case TOWN_GROWTH_DESERT:
3066 if (GetTropicZone(t->xy) == TROPICZONE_DESERT && t->received[i].old_act == 0 && t->cache.population > 60) return;
3067 break;
3068 default:
3069 if (t->goal[i] > t->received[i].old_act) return;
3070 break;
3071 }
3072 }
3073 }
3074
3075 if ((t->growth_rate & TOWN_GROW_RATE_CUSTOM) != 0) {
3076 if (t->growth_rate != TOWN_GROW_RATE_CUSTOM_NONE) SetBit(t->flags, TOWN_IS_GROWING);
3077 SetWindowDirty(WC_TOWN_VIEW, t->index);
3078 return;
3079 }
3080
3085 static const uint16 _grow_count_values[2][6] = {
3086 { 120, 120, 120, 100, 80, 60 }, // Fund new buildings has been activated
3087 { 320, 420, 300, 220, 160, 100 } // Normal values
3088 };
3089
3090 int n = 0;
3091
3092 const Station *st;
3093 FOR_ALL_STATIONS(st) {
3094 if (DistanceSquare(st->xy, t->xy) <= t->cache.squared_town_zone_radius[0]) {
3095 if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
3096 n++;
3097 }
3098 }
3099 }
3100
3101 uint16 m;
3102
3103 if (t->fund_buildings_months != 0) {
3104 m = _grow_count_values[0][min(n, 5)];
3105 } else {
3106 m = _grow_count_values[1][min(n, 5)];
3107 if (n == 0 && !Chance16(1, 12)) return;
3108 }
3109
3110 /* Use the normal growth rate values if new buildings have been funded in
3111 * this town and the growth rate is set to none. */
3112 uint growth_multiplier = _settings_game.economy.town_growth_rate != 0 ? _settings_game.economy.town_growth_rate - 1 : 1;
3113
3114 m >>= growth_multiplier;
3115 if (t->larger_town) m /= 2;
3116
3117 t->growth_rate = m / (t->cache.num_houses / 50 + 1);
3118 t->grow_counter = min(t->growth_rate, t->grow_counter);
3119
3120 SetBit(t->flags, TOWN_IS_GROWING);
3121 SetWindowDirty(WC_TOWN_VIEW, t->index);
3122 }
3123
3124 static void UpdateTownAmounts(Town *t)
3125 {
3126 for (CargoID i = 0; i < NUM_CARGO; i++) t->supplied[i].NewMonth();
3127 for (int i = TE_BEGIN; i < TE_END; i++) t->received[i].NewMonth();
3128 if (t->fund_buildings_months != 0) t->fund_buildings_months--;
3129
3130 SetWindowDirty(WC_TOWN_VIEW, t->index);
3131 }
3132
3133 static void UpdateTownUnwanted(Town *t)
3134 {
3135 const Company *c;
3136
3137 FOR_ALL_COMPANIES(c) {
3138 if (t->unwanted[c->index] > 0) t->unwanted[c->index]--;
3139 }
3140 }
3141
3148 CommandCost CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags)
3149 {
3150 if (!Company::IsValidID(_current_company) || (flags & DC_NO_TEST_TOWN_RATING)) return CommandCost();
3151
3152 Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
3153 if (t == NULL) return CommandCost();
3154
3155 if (t->ratings[_current_company] > RATING_VERYPOOR) return CommandCost();
3156
3157 SetDParam(0, t->index);
3158 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
3159 }
3160
3169 Town *CalcClosestTownFromTile(TileIndex tile, uint threshold)
3170 {
3171 Town *t;
3172 uint best = threshold;
3173 Town *best_town = NULL;
3174
3175 FOR_ALL_TOWNS(t) {
3176 uint dist = DistanceManhattan(tile, t->xy);
3177 if (dist < best) {
3178 best = dist;
3179 best_town = t;
3180 }
3181 }
3182
3183 return best_town;
3184 }
3185
3194 Town *ClosestTownFromTile(TileIndex tile, uint threshold)
3195 {
3196 switch (GetTileType(tile)) {
3197 case MP_ROAD:
3198 if (IsRoadDepot(tile)) return CalcClosestTownFromTile(tile, threshold);
3199
3200 if (!HasTownOwnedRoad(tile)) {
3201 TownID tid = GetTownIndex(tile);
3202
3203 if (tid == (TownID)INVALID_TOWN) {
3204 /* in the case we are generating "many random towns", this value may be INVALID_TOWN */
3205 if (_generating_world) return CalcClosestTownFromTile(tile, threshold);
3206 assert(Town::GetNumItems() == 0);
3207 return NULL;
3208 }
3209
3210 assert(Town::IsValidID(tid));
3211 Town *town = Town::Get(tid);
3212
3213 if (DistanceManhattan(tile, town->xy) >= threshold) town = NULL;
3214
3215 return town;
3216 }
3217 /* FALL THROUGH */
3218
3219 case MP_HOUSE:
3220 return Town::GetByTile(tile);
3221
3222 default:
3223 return CalcClosestTownFromTile(tile, threshold);
3224 }
3225 }
3226
3227 static bool _town_rating_test = false;
3228 static SmallMap<const Town *, int, 4> _town_test_ratings;
3229
3235 void SetTownRatingTestMode(bool mode)
3236 {
3237 static int ref_count = 0; // Number of times test-mode is switched on.
3238 if (mode) {
3239 if (ref_count == 0) {
3240 _town_test_ratings.Clear();
3241 }
3242 ref_count++;
3243 } else {
3244 assert(ref_count > 0);
3245 ref_count--;
3246 }
3247 _town_rating_test = !(ref_count == 0);
3248 }
3249
3255 static int GetRating(const Town *t)
3256 {
3257 if (_town_rating_test) {
3258 SmallMap<const Town *, int>::iterator it = _town_test_ratings.Find(t);
3259 if (it != _town_test_ratings.End()) {
3260 return it->second;
3261 }
3262 }
3263 return t->ratings[_current_company];
3264 }
3265
3273 void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
3274 {
3275 /* if magic_bulldozer cheat is active, town doesn't penalize for removing stuff */
3276 if (t == NULL || (flags & DC_NO_MODIFY_TOWN_RATING) ||
3277 !Company::IsValidID(_current_company) ||
3278 (_cheats.magic_bulldozer.value && add < 0)) {
3279 return;
3280 }
3281
3282 int rating = GetRating(t);
3283 if (add < 0) {
3284 if (rating > max) {
3285 rating += add;
3286 if (rating < max) rating = max;
3287 }
3288 } else {
3289 if (rating < max) {
3290 rating += add;
3291 if (rating > max) rating = max;
3292 }
3293 }
3294 if (_town_rating_test) {
3295 _town_test_ratings[t] = rating;
3296 } else {
3297 SetBit(t->have_ratings, _current_company);
3298 t->ratings[_current_company] = rating;
3299 SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
3300 }
3301 }
3302
3310 CommandCost CheckforTownRating(DoCommandFlag flags, Town *t, TownRatingCheckType type)
3311 {
3312 /* if magic_bulldozer cheat is active, town doesn't restrict your destructive actions */
3313 if (t == NULL || !Company::IsValidID(_current_company) ||
3314 _cheats.magic_bulldozer.value || (flags & DC_NO_TEST_TOWN_RATING)) {
3315 return CommandCost();
3316 }
3317
3318 /* minimum rating needed to be allowed to remove stuff */
3319 static const int needed_rating[][TOWN_RATING_CHECK_TYPE_COUNT] = {
3320 /* ROAD_REMOVE, TUNNELBRIDGE_REMOVE */
3321 { RATING_ROAD_NEEDED_PERMISSIVE, RATING_TUNNEL_BRIDGE_NEEDED_PERMISSIVE}, // Permissive
3322 { RATING_ROAD_NEEDED_NEUTRAL, RATING_TUNNEL_BRIDGE_NEEDED_NEUTRAL}, // Neutral
3323 { RATING_ROAD_NEEDED_HOSTILE, RATING_TUNNEL_BRIDGE_NEEDED_HOSTILE}, // Hostile
3324 };
3325
3326 /* check if you're allowed to remove the road/bridge/tunnel
3327 * owned by a town no removal if rating is lower than ... depends now on
3328 * difficulty setting. Minimum town rating selected by difficulty level
3329 */
3330 int needed = needed_rating[_settings_game.difficulty.town_council_tolerance][type];
3331
3332 if (GetRating(t) < needed) {
3333 SetDParam(0, t->index);
3334 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
3335 }
3336
3337 return CommandCost();
3338 }
3339
3340 void TownsMonthlyLoop()
3341 {
3342 Town *t;
3343
3344 FOR_ALL_TOWNS(t) {
3345 if (t->road_build_months != 0) t->road_build_months--;
3346
3347 if (t->exclusive_counter != 0) {
3348 if (--t->exclusive_counter == 0) t->exclusivity = INVALID_COMPANY;
3349 }
3350
3351 UpdateTownAmounts(t);
3352 UpdateTownRating(t);
3353 UpdateTownGrowRate(t);
3354 UpdateTownUnwanted(t);
3355 UpdateTownCargoes(t);
3356 }
3357
3358 UpdateTownCargoBitmap();
3359 }
3360
3361 void TownsYearlyLoop()
3362 {
3363 /* Increment house ages */
3364 for (TileIndex t = 0; t < MapSize(); t++) {
3365 if (!IsTileType(t, MP_HOUSE)) continue;
3366 IncrementHouseAge(t);
3367 }
3368 }
3369
3370 static CommandCost TerraformTile_Town(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
3371 {
3372 if (AutoslopeEnabled()) {
3373 HouseID house = GetHouseType(tile);
3374 GetHouseNorthPart(house); // modifies house to the ID of the north tile
3375 const HouseSpec *hs = HouseSpec::Get(house);
3376
3377 /* Here we differ from TTDP by checking TILE_NOT_SLOPED */
3378 if (((hs->building_flags & TILE_NOT_SLOPED) == 0) && !IsSteepSlope(tileh_new) &&
3379 (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
3380 bool allow_terraform = true;
3381
3382 /* Call the autosloping callback per tile, not for the whole building at once. */
3383 house = GetHouseType(tile);
3384 hs = HouseSpec::Get(house);
3385 if (HasBit(hs->callback_mask, CBM_HOUSE_AUTOSLOPE)) {
3386 /* If the callback fails, allow autoslope. */
3387 uint16 res = GetHouseCallback(CBID_HOUSE_AUTOSLOPE, 0, 0, house, Town::GetByTile(tile), tile);
3388 if (res != CALLBACK_FAILED && ConvertBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_AUTOSLOPE, res)) allow_terraform = false;
3389 }
3390
3391 if (allow_terraform) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
3392 }
3393 }
3394
3395 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
3396 }
3397
3399 extern const TileTypeProcs _tile_type_town_procs = {
3400 DrawTile_Town, // draw_tile_proc
3401 GetSlopePixelZ_Town, // get_slope_z_proc
3402 ClearTile_Town, // clear_tile_proc
3403 AddAcceptedCargo_Town, // add_accepted_cargo_proc
3404 GetTileDesc_Town, // get_tile_desc_proc
3405 GetTileTrackStatus_Town, // get_tile_track_status_proc
3406 NULL, // click_tile_proc
3407 AnimateTile_Town, // animate_tile_proc
3408 TileLoop_Town, // tile_loop_proc
3409 ChangeTileOwner_Town, // change_tile_owner_proc
3410 AddProducedCargo_Town, // add_produced_cargo_proc
3411 NULL, // vehicle_enter_tile_proc
3412 GetFoundation_Town, // get_foundation_proc
3413 TerraformTile_Town, // terraform_tile_proc
3414 };
3415
3416
3417 HouseSpec _house_specs[NUM_HOUSES];
3418
3419 void ResetHouses()
3420 {
3421 memset(&_house_specs, 0, sizeof(_house_specs));
3422 memcpy(&_house_specs, &_original_house_specs, sizeof(_original_house_specs));
3423
3424 /* Reset any overrides that have been set. */
3425 _house_mngr.ResetOverride();
3426 }