-
-
Notifications
You must be signed in to change notification settings - Fork 844
/
town_cmd.cpp
3968 lines (3350 loc) · 129 KB
/
town_cmd.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is part of OpenTTD.
* 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.
* 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.
* 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/>.
*/
/** @file town_cmd.cpp Handling of town tiles. */
#include "stdafx.h"
#include "road.h"
#include "road_internal.h" /* Cleaning up road bits */
#include "road_cmd.h"
#include "landscape.h"
#include "viewport_func.h"
#include "viewport_kdtree.h"
#include "command_func.h"
#include "company_func.h"
#include "industry.h"
#include "station_base.h"
#include "waypoint_base.h"
#include "station_kdtree.h"
#include "company_base.h"
#include "news_func.h"
#include "error.h"
#include "object.h"
#include "genworld.h"
#include "newgrf_debug.h"
#include "newgrf_house.h"
#include "newgrf_text.h"
#include "autoslope.h"
#include "tunnelbridge_map.h"
#include "strings_func.h"
#include "window_func.h"
#include "string_func.h"
#include "newgrf_cargo.h"
#include "cheat_type.h"
#include "animated_tile_func.h"
#include "subsidy_func.h"
#include "core/pool_func.hpp"
#include "town.h"
#include "town_kdtree.h"
#include "townname_func.h"
#include "core/random_func.hpp"
#include "core/backup_type.hpp"
#include "depot_base.h"
#include "object_map.h"
#include "object_base.h"
#include "ai/ai.hpp"
#include "game/game.hpp"
#include "town_cmd.h"
#include "landscape_cmd.h"
#include "road_cmd.h"
#include "terraform_cmd.h"
#include "tunnelbridge_cmd.h"
#include "timer/timer.h"
#include "timer/timer_game_calendar.h"
#include "timer/timer_game_economy.h"
#include "timer/timer_game_tick.h"
#include "table/strings.h"
#include "table/town_land.h"
#include "safeguards.h"
/* Initialize the town-pool */
TownPool _town_pool("Town");
INSTANTIATE_POOL_METHODS(Town)
TownKdtree _town_kdtree(&Kdtree_TownXYFunc);
void RebuildTownKdtree()
{
std::vector<TownID> townids;
for (const Town *town : Town::Iterate()) {
townids.push_back(town->index);
}
_town_kdtree.Build(townids.begin(), townids.end());
}
/**
* Check if a town 'owns' a bridge.
* Bridges do not directly have an owner, so we check the tiles adjacent to the bridge ends.
* If either adjacent tile belongs to the town then it will be assumed that the town built
* the bridge.
* @param tile The bridge tile to test
* @param t The town we are interested in
* @return true If town 'owns' a bridge.
*/
static bool TestTownOwnsBridge(TileIndex tile, const Town *t)
{
if (!IsTileOwner(tile, OWNER_TOWN)) return false;
TileIndex adjacent = tile + TileOffsByDiagDir(ReverseDiagDir(GetTunnelBridgeDirection(tile)));
bool town_owned = IsTileType(adjacent, MP_ROAD) && IsTileOwner(adjacent, OWNER_TOWN) && GetTownIndex(adjacent) == t->index;
if (!town_owned) {
/* Or other adjacent road */
adjacent = tile + TileOffsByDiagDir(ReverseDiagDir(GetTunnelBridgeDirection(GetOtherTunnelBridgeEnd(tile))));
town_owned = IsTileType(adjacent, MP_ROAD) && IsTileOwner(adjacent, OWNER_TOWN) && GetTownIndex(adjacent) == t->index;
}
return town_owned;
}
Town::~Town()
{
if (CleaningPool()) return;
/* Delete town authority window
* and remove from list of sorted towns */
CloseWindowById(WC_TOWN_VIEW, this->index);
#ifdef WITH_ASSERT
/* Check no industry is related to us. */
for (const Industry *i : Industry::Iterate()) {
assert(i->town != this);
}
/* ... and no object is related to us. */
for (const Object *o : Object::Iterate()) {
assert(o->town != this);
}
#endif /* WITH_ASSERT */
/* Check no tile is related to us. */
for (TileIndex tile = 0; tile < Map::Size(); ++tile) {
switch (GetTileType(tile)) {
case MP_HOUSE:
assert(GetTownIndex(tile) != this->index);
break;
case MP_ROAD:
assert(!HasTownOwnedRoad(tile) || GetTownIndex(tile) != this->index);
break;
case MP_TUNNELBRIDGE:
assert(!TestTownOwnsBridge(tile, this));
break;
default:
break;
}
}
/* Clear the persistent storage list. */
this->psa_list.clear();
DeleteSubsidyWith(SourceType::Town, this->index);
DeleteNewGRFInspectWindow(GSF_FAKE_TOWNS, this->index);
CargoPacket::InvalidateAllFrom(SourceType::Town, this->index);
MarkWholeScreenDirty();
}
/**
* Invalidating of the "nearest town cache" has to be done
* after removing item from the pool.
*/
void Town::PostDestructor(size_t)
{
InvalidateWindowData(WC_TOWN_DIRECTORY, 0, TDIWD_FORCE_REBUILD);
UpdateNearestTownForRoadTiles(false);
/* Give objects a new home! */
for (Object *o : Object::Iterate()) {
if (o->town == nullptr) o->town = CalcClosestTownFromTile(o->location.tile, UINT_MAX);
}
}
/**
* Assign the town layout.
* @param layout The desired layout. If TL_RANDOM, we pick one based on TileHash.
*/
void Town::InitializeLayout(TownLayout layout)
{
if (layout != TL_RANDOM) {
this->layout = layout;
return;
}
this->layout = static_cast<TownLayout>(TileHash(TileX(this->xy), TileY(this->xy)) % (NUM_TLS - 1));
}
/**
* Return a random valid town.
* @return A random town, or nullptr if there are no towns.
*/
/* static */ Town *Town::GetRandom()
{
if (Town::GetNumItems() == 0) return nullptr;
int num = RandomRange((uint16_t)Town::GetNumItems());
size_t index = MAX_UVALUE(size_t);
while (num >= 0) {
num--;
index++;
/* Make sure we have a valid town */
while (!Town::IsValidID(index)) {
index++;
assert(index < Town::GetPoolSize());
}
}
return Town::Get(index);
}
void Town::FillCachedName() const
{
this->cached_name = GetTownName(this);
}
/**
* Get the cost for removing this house.
* @return The cost adjusted for inflation, etc.
*/
Money HouseSpec::GetRemovalCost() const
{
return (_price[PR_CLEAR_HOUSE] * this->removal_cost) >> 8;
}
/* Local */
static int _grow_town_result;
/* The possible states of town growth. */
enum TownGrowthResult {
GROWTH_SUCCEED = -1,
GROWTH_SEARCH_STOPPED = 0
// GROWTH_SEARCH_RUNNING >= 1
};
static bool BuildTownHouse(Town *t, TileIndex tile);
static Town *CreateRandomTown(uint attempts, uint32_t townnameparts, TownSize size, bool city, TownLayout layout);
static void TownDrawHouseLift(const TileInfo *ti)
{
AddChildSpriteScreen(SPR_LIFT, PAL_NONE, 14, 60 - GetLiftPosition(ti->tile));
}
typedef void TownDrawTileProc(const TileInfo *ti);
static TownDrawTileProc * const _town_draw_tile_procs[1] = {
TownDrawHouseLift
};
/**
* Return a random direction
*
* @return a random direction
*/
static inline DiagDirection RandomDiagDir()
{
return (DiagDirection)(RandomRange(DIAGDIR_END));
}
/**
* Draw a house and its tile. This is a tile callback routine.
* @param ti TileInfo of the tile to draw
*/
static void DrawTile_Town(TileInfo *ti)
{
HouseID house_id = GetHouseType(ti->tile);
if (house_id >= NEW_HOUSE_OFFSET) {
/* Houses don't necessarily need new graphics. If they don't have a
* spritegroup associated with them, then the sprite for the substitute
* house id is drawn instead. */
if (HouseSpec::Get(house_id)->grf_prop.spritegroup[0] != nullptr) {
DrawNewHouseTile(ti, house_id);
return;
} else {
house_id = HouseSpec::Get(house_id)->grf_prop.subst_id;
}
}
/* Retrieve pointer to the draw town tile struct */
const DrawBuildingsTileStruct *dcts = &_town_draw_tile_data[house_id << 4 | TileHash2Bit(ti->x, ti->y) << 2 | GetHouseBuildingStage(ti->tile)];
if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
DrawGroundSprite(dcts->ground.sprite, dcts->ground.pal);
/* If houses are invisible, do not draw the upper part */
if (IsInvisibilitySet(TO_HOUSES)) return;
/* Add a house on top of the ground? */
SpriteID image = dcts->building.sprite;
if (image != 0) {
AddSortableSpriteToDraw(image, dcts->building.pal,
ti->x + dcts->subtile_x,
ti->y + dcts->subtile_y,
dcts->width,
dcts->height,
dcts->dz,
ti->z,
IsTransparencySet(TO_HOUSES)
);
if (IsTransparencySet(TO_HOUSES)) return;
}
{
int proc = dcts->draw_proc - 1;
if (proc >= 0) _town_draw_tile_procs[proc](ti);
}
}
static int GetSlopePixelZ_Town(TileIndex tile, uint, uint, bool)
{
return GetTileMaxPixelZ(tile);
}
/**
* Get the foundation for a house. This is a tile callback routine.
* @param tile The tile to find a foundation for.
* @param tileh The slope of the tile.
*/
static Foundation GetFoundation_Town(TileIndex tile, Slope tileh)
{
HouseID hid = GetHouseType(tile);
/* For NewGRF house tiles we might not be drawing a foundation. We need to
* account for this, as other structures should
* draw the wall of the foundation in this case.
*/
if (hid >= NEW_HOUSE_OFFSET) {
const HouseSpec *hs = HouseSpec::Get(hid);
if (hs->grf_prop.spritegroup[0] != nullptr && HasBit(hs->callback_mask, CBM_HOUSE_DRAW_FOUNDATIONS)) {
uint32_t callback_res = GetHouseCallback(CBID_HOUSE_DRAW_FOUNDATIONS, 0, 0, hid, Town::GetByTile(tile), tile);
if (callback_res != CALLBACK_FAILED && !ConvertBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_DRAW_FOUNDATIONS, callback_res)) return FOUNDATION_NONE;
}
}
return FlatteningFoundation(tileh);
}
/**
* Animate a tile for a town.
* Only certain houses can be animated.
* The newhouses animation supersedes regular ones.
* @param tile TileIndex of the house to animate.
*/
static void AnimateTile_Town(TileIndex tile)
{
if (GetHouseType(tile) >= NEW_HOUSE_OFFSET) {
AnimateNewHouseTile(tile);
return;
}
if (TimerGameTick::counter & 3) return;
/* If the house is not one with a lift anymore, then stop this animating.
* Not exactly sure when this happens, but probably when a house changes.
* Before this was just a return...so it'd leak animated tiles..
* That bug seems to have been here since day 1?? */
if (!(HouseSpec::Get(GetHouseType(tile))->building_flags & BUILDING_IS_ANIMATED)) {
DeleteAnimatedTile(tile);
return;
}
if (!LiftHasDestination(tile)) {
uint i;
/* Building has 6 floors, number 0 .. 6, where 1 is illegal.
* This is due to the fact that the first floor is, in the graphics,
* the height of 2 'normal' floors.
* Furthermore, there are 6 lift positions from floor N (incl) to floor N + 1 (excl) */
do {
i = RandomRange(7);
} while (i == 1 || i * 6 == GetLiftPosition(tile));
SetLiftDestination(tile, i);
}
int pos = GetLiftPosition(tile);
int dest = GetLiftDestination(tile) * 6;
pos += (pos < dest) ? 1 : -1;
SetLiftPosition(tile, pos);
if (pos == dest) {
HaltLift(tile);
DeleteAnimatedTile(tile);
}
MarkTileDirtyByTile(tile);
}
/**
* Determines if a town is close to a tile.
* @param tile TileIndex of the tile to query.
* @param dist The maximum distance to be accepted.
* @returns true if the tile is within the specified distance.
*/
static bool IsCloseToTown(TileIndex tile, uint dist)
{
if (_town_kdtree.Count() == 0) return false;
Town *t = Town::Get(_town_kdtree.FindNearest(TileX(tile), TileY(tile)));
return DistanceManhattan(tile, t->xy) < dist;
}
/** Resize the sign (label) of the town after it changes population. */
void Town::UpdateVirtCoord()
{
Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
if (this->cache.sign.kdtree_valid) _viewport_sign_kdtree.Remove(ViewportSignKdtreeItem::MakeTown(this->index));
SetDParam(0, this->index);
SetDParam(1, this->cache.population);
this->cache.sign.UpdatePosition(pt.x, pt.y - 24 * ZOOM_LVL_BASE,
_settings_client.gui.population_in_label ? STR_VIEWPORT_TOWN_POP : STR_VIEWPORT_TOWN,
STR_VIEWPORT_TOWN_TINY_WHITE);
_viewport_sign_kdtree.Insert(ViewportSignKdtreeItem::MakeTown(this->index));
SetWindowDirty(WC_TOWN_VIEW, this->index);
}
/** Update the virtual coords needed to draw the town sign for all towns. */
void UpdateAllTownVirtCoords()
{
for (Town *t : Town::Iterate()) {
t->UpdateVirtCoord();
}
}
/** Clear the cached_name of all towns. */
void ClearAllTownCachedNames()
{
for (Town *t : Town::Iterate()) {
t->cached_name.clear();
}
}
/**
* Change the town's population as recorded in the town cache, town label, and town directory.
* @param t The town which has changed.
* @param mod The population change (can be positive or negative).
*/
static void ChangePopulation(Town *t, int mod)
{
t->cache.population += mod;
InvalidateWindowData(WC_TOWN_VIEW, t->index); // Cargo requirements may appear/vanish for small populations
if (_settings_client.gui.population_in_label) t->UpdateVirtCoord();
InvalidateWindowData(WC_TOWN_DIRECTORY, 0, TDIWD_POPULATION_CHANGE);
}
/**
* Get the total population, the sum of all towns in the world.
* @return The calculated population of the world
*/
uint32_t GetWorldPopulation()
{
uint32_t pop = 0;
for (const Town *t : Town::Iterate()) pop += t->cache.population;
return pop;
}
/**
* Remove stations from nearby station list if a town is no longer in the catchment area of each.
* To improve performance only checks stations that cover the provided house area (doesn't need to contain an actual house).
* @param t Town to work on.
* @param tile Location of house area (north tile).
* @param flags BuildingFlags containing the size of house area.
*/
static void RemoveNearbyStations(Town *t, TileIndex tile, BuildingFlags flags)
{
for (StationList::iterator it = t->stations_near.begin(); it != t->stations_near.end(); /* incremented inside loop */) {
const Station *st = *it;
bool covers_area = st->TileIsInCatchment(tile);
if (flags & BUILDING_2_TILES_Y) covers_area |= st->TileIsInCatchment(tile + TileDiffXY(0, 1));
if (flags & BUILDING_2_TILES_X) covers_area |= st->TileIsInCatchment(tile + TileDiffXY(1, 0));
if (flags & BUILDING_HAS_4_TILES) covers_area |= st->TileIsInCatchment(tile + TileDiffXY(1, 1));
if (covers_area && !st->CatchmentCoversTown(t->index)) {
it = t->stations_near.erase(it);
} else {
++it;
}
}
}
/**
* Helper function for house construction stage progression.
* @param tile TileIndex of the house (or parts of it) to construct.
*/
static void AdvanceSingleHouseConstruction(TileIndex tile)
{
assert(IsTileType(tile, MP_HOUSE));
/* Progress in construction stages */
IncHouseConstructionTick(tile);
if (GetHouseConstructionTick(tile) != 0) return;
AnimateNewHouseConstruction(tile);
if (IsHouseCompleted(tile)) {
/* Now that construction is complete, we can add the population of the
* building to the town. */
ChangePopulation(Town::GetByTile(tile), HouseSpec::Get(GetHouseType(tile))->population);
ResetHouseAge(tile);
}
MarkTileDirtyByTile(tile);
}
/**
* Increase the construction stage of a house.
* @param tile The tile of the house under construction.
*/
static void AdvanceHouseConstruction(TileIndex tile)
{
uint flags = HouseSpec::Get(GetHouseType(tile))->building_flags;
if (flags & BUILDING_HAS_1_TILE) AdvanceSingleHouseConstruction(TileAddXY(tile, 0, 0));
if (flags & BUILDING_2_TILES_Y) AdvanceSingleHouseConstruction(TileAddXY(tile, 0, 1));
if (flags & BUILDING_2_TILES_X) AdvanceSingleHouseConstruction(TileAddXY(tile, 1, 0));
if (flags & BUILDING_HAS_4_TILES) AdvanceSingleHouseConstruction(TileAddXY(tile, 1, 1));
}
/**
* Generate cargo for a house, scaled by the current economy scale.
* @param t The current town.
* @param ct Type of cargo to generate, usually CT_PASSENGERS or CT_MAIL.
* @param amount The number of cargo units.
* @param stations Available stations for this house.
* @param affected_by_recession Is this cargo halved during recessions?
*/
static void TownGenerateCargo(Town *t, CargoID ct, uint amount, StationFinder &stations, bool affected_by_recession)
{
if (amount == 0) return;
/* All production is halved during a recession (except for NewGRF-supplied town cargo). */
if (affected_by_recession && EconomyIsInRecession()) {
amount = (amount + 1) >> 1;
}
/* Scale by cargo scale setting. */
amount = ScaleByCargoScale(amount, true);
/* Actually generate cargo and update town statistics. */
t->supplied[ct].new_max += amount;
t->supplied[ct].new_act += MoveGoodsToStation(ct, amount, SourceType::Town, t->index, stations.GetStations());;
}
/**
* Generate cargo for a house using the original algorithm.
* @param t The current town.
* @param tpe The town production effect.
* @param rate The town's product rate for this production.
* @param stations Available stations for this house.
*/
static void TownGenerateCargoOriginal(Town *t, TownProductionEffect tpe, uint8_t rate, StationFinder &stations)
{
for (const CargoSpec *cs : CargoSpec::town_production_cargoes[tpe]) {
uint32_t r = Random();
if (GB(r, 0, 8) < rate) {
CargoID cid = cs->Index();
uint amt = (GB(r, 0, 8) * cs->town_production_multiplier / TOWN_PRODUCTION_DIVISOR) / 8 + 1;
TownGenerateCargo(t, cid, amt, stations, true);
}
}
}
/**
* Generate cargo for a house using the binominal algorithm.
* @param t The current town.
* @param tpe The town production effect.
* @param rate The town's product rate for this production.
* @param stations Available stations for this house.
*/
static void TownGenerateCargoBinominal(Town *t, TownProductionEffect tpe, uint8_t rate, StationFinder &stations)
{
for (const CargoSpec *cs : CargoSpec::town_production_cargoes[tpe]) {
CargoID cid = cs->Index();
uint32_t r = Random();
/* Make a bitmask with up to 32 bits set, one for each potential pax. */
int genmax = (rate + 7) / 8;
uint32_t genmask = (genmax >= 32) ? 0xFFFFFFFF : ((1 << genmax) - 1);
/* Mask random value by potential pax and count number of actual pax. */
uint amt = CountBits(r & genmask) * cs->town_production_multiplier / TOWN_PRODUCTION_DIVISOR;
TownGenerateCargo(t, cid, amt, stations, true);
}
}
/**
* Tile callback function.
*
* Tile callback function. Periodic tick handler for the tiles of a town.
* @param tile been asked to do its stuff
*/
static void TileLoop_Town(TileIndex tile)
{
HouseID house_id = GetHouseType(tile);
/* NewHouseTileLoop returns false if Callback 21 succeeded, i.e. the house
* doesn't exist any more, so don't continue here. */
if (house_id >= NEW_HOUSE_OFFSET && !NewHouseTileLoop(tile)) return;
if (!IsHouseCompleted(tile)) {
/* Construction is not completed, so we advance a construction stage. */
AdvanceHouseConstruction(tile);
return;
}
const HouseSpec *hs = HouseSpec::Get(house_id);
/* If the lift has a destination, it is already an animated tile. */
if ((hs->building_flags & BUILDING_IS_ANIMATED) &&
house_id < NEW_HOUSE_OFFSET &&
!LiftHasDestination(tile) &&
Chance16(1, 2)) {
AddAnimatedTile(tile);
}
Town *t = Town::GetByTile(tile);
uint32_t r = Random();
StationFinder stations(TileArea(tile, 1, 1));
if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
for (uint i = 0; i < 256; i++) {
uint16_t callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, r, house_id, t, tile);
if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
if (!IsValidCargoID(cargo)) continue;
uint amt = GB(callback, 0, 8);
if (amt == 0) continue;
/* NewGRF-supplied town cargos are not affected by recessions. */
TownGenerateCargo(t, cargo, amt, stations, false);
}
} else {
switch (_settings_game.economy.town_cargogen_mode) {
case TCGM_ORIGINAL:
/* Original (quadratic) cargo generation algorithm */
TownGenerateCargoOriginal(t, TPE_PASSENGERS, hs->population, stations);
TownGenerateCargoOriginal(t, TPE_MAIL, hs->mail_generation, stations);
break;
case TCGM_BITCOUNT:
/* Binomial distribution per tick, by a series of coin flips */
/* Reduce generation rate to a 1/4, using tile bits to spread out distribution.
* As tick counter is incremented by 256 between each call, we ignore the lower 8 bits. */
if (GB(TimerGameTick::counter, 8, 2) == GB(tile.base(), 0, 2)) {
TownGenerateCargoBinominal(t, TPE_PASSENGERS, hs->population, stations);
TownGenerateCargoBinominal(t, TPE_MAIL, hs->mail_generation, stations);
}
break;
default:
NOT_REACHED();
}
}
Backup<CompanyID> cur_company(_current_company, OWNER_TOWN);
if ((hs->building_flags & BUILDING_HAS_1_TILE) &&
HasBit(t->flags, TOWN_IS_GROWING) &&
CanDeleteHouse(tile) &&
GetHouseAge(tile) >= hs->minimum_life &&
--t->time_until_rebuild == 0) {
t->time_until_rebuild = GB(r, 16, 8) + 192;
ClearTownHouse(t, tile);
/* Rebuild with another house? */
if (GB(r, 24, 8) >= 12) {
/* If we are multi-tile houses, make sure to replace the house
* closest to city center. If we do not do this, houses tend to
* wander away from roads and other houses. */
if (hs->building_flags & BUILDING_HAS_2_TILES) {
/* House tiles are always the most north tile. Move the new
* house to the south if we are north of the city center. */
TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
int x = Clamp(grid_pos.x, 0, 1);
int y = Clamp(grid_pos.y, 0, 1);
if (hs->building_flags & TILE_SIZE_2x2) {
tile = TileAddXY(tile, x, y);
} else if (hs->building_flags & TILE_SIZE_1x2) {
tile = TileAddXY(tile, 0, y);
} else if (hs->building_flags & TILE_SIZE_2x1) {
tile = TileAddXY(tile, x, 0);
}
}
BuildTownHouse(t, tile);
}
}
cur_company.Restore();
}
/**
* Callback function to clear a house tile.
* @param tile The tile to clear.
* @param flags Type of operation.
* @return The cost of this operation or an error.
*/
static CommandCost ClearTile_Town(TileIndex tile, DoCommandFlag flags)
{
if (flags & DC_AUTO) return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
if (!CanDeleteHouse(tile)) return CMD_ERROR;
const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
CommandCost cost(EXPENSES_CONSTRUCTION);
cost.AddCost(hs->GetRemovalCost());
int rating = hs->remove_rating_decrease;
Town *t = Town::GetByTile(tile);
if (Company::IsValidID(_current_company)) {
if (rating > t->ratings[_current_company] && !(flags & DC_NO_TEST_TOWN_RATING) &&
!_cheats.magic_bulldozer.value && _settings_game.difficulty.town_council_tolerance != TOWN_COUNCIL_PERMISSIVE) {
SetDParam(0, t->index);
return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
}
}
ChangeTownRating(t, -rating, RATING_HOUSE_MINIMUM, flags);
if (flags & DC_EXEC) {
ClearTownHouse(t, tile);
}
return cost;
}
static void AddProducedCargo_Town(TileIndex tile, CargoArray &produced)
{
HouseID house_id = GetHouseType(tile);
const HouseSpec *hs = HouseSpec::Get(house_id);
Town *t = Town::GetByTile(tile);
if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
for (uint i = 0; i < 256; i++) {
uint16_t callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, 0, house_id, t, tile);
if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
if (!IsValidCargoID(cargo)) continue;
produced[cargo]++;
}
} else {
if (hs->population > 0) {
for (const CargoSpec *cs : CargoSpec::town_production_cargoes[TPE_PASSENGERS]) {
produced[cs->Index()]++;
}
}
if (hs->mail_generation > 0) {
for (const CargoSpec *cs : CargoSpec::town_production_cargoes[TPE_MAIL]) {
produced[cs->Index()]++;
}
}
}
}
static inline void AddAcceptedCargoSetMask(CargoID cargo, uint amount, CargoArray &acceptance, CargoTypes *always_accepted)
{
if (!IsValidCargoID(cargo) || amount == 0) return;
acceptance[cargo] += amount;
SetBit(*always_accepted, cargo);
}
static void AddAcceptedCargo_Town(TileIndex tile, CargoArray &acceptance, CargoTypes *always_accepted)
{
const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
CargoID accepts[lengthof(hs->accepts_cargo)];
/* Set the initial accepted cargo types */
for (uint8_t i = 0; i < lengthof(accepts); i++) {
accepts[i] = hs->accepts_cargo[i];
}
/* Check for custom accepted cargo types */
if (HasBit(hs->callback_mask, CBM_HOUSE_ACCEPT_CARGO)) {
uint16_t callback = GetHouseCallback(CBID_HOUSE_ACCEPT_CARGO, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
if (callback != CALLBACK_FAILED) {
/* Replace accepted cargo types with translated values from callback */
accepts[0] = GetCargoTranslation(GB(callback, 0, 5), hs->grf_prop.grffile);
accepts[1] = GetCargoTranslation(GB(callback, 5, 5), hs->grf_prop.grffile);
accepts[2] = GetCargoTranslation(GB(callback, 10, 5), hs->grf_prop.grffile);
}
}
/* Check for custom cargo acceptance */
if (HasBit(hs->callback_mask, CBM_HOUSE_CARGO_ACCEPTANCE)) {
uint16_t callback = GetHouseCallback(CBID_HOUSE_CARGO_ACCEPTANCE, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
if (callback != CALLBACK_FAILED) {
AddAcceptedCargoSetMask(accepts[0], GB(callback, 0, 4), acceptance, always_accepted);
AddAcceptedCargoSetMask(accepts[1], GB(callback, 4, 4), acceptance, always_accepted);
if (_settings_game.game_creation.landscape != LT_TEMPERATE && HasBit(callback, 12)) {
/* The 'S' bit indicates food instead of goods */
AddAcceptedCargoSetMask(GetCargoIDByLabel(CT_FOOD), GB(callback, 8, 4), acceptance, always_accepted);
} else {
AddAcceptedCargoSetMask(accepts[2], GB(callback, 8, 4), acceptance, always_accepted);
}
return;
}
}
/* No custom acceptance, so fill in with the default values */
for (uint8_t i = 0; i < lengthof(accepts); i++) {
AddAcceptedCargoSetMask(accepts[i], hs->cargo_acceptance[i], acceptance, always_accepted);
}
}
static void GetTileDesc_Town(TileIndex tile, TileDesc *td)
{
const HouseID house = GetHouseType(tile);
const HouseSpec *hs = HouseSpec::Get(house);
bool house_completed = IsHouseCompleted(tile);
td->str = hs->building_name;
uint16_t callback_res = GetHouseCallback(CBID_HOUSE_CUSTOM_NAME, house_completed ? 1 : 0, 0, house, Town::GetByTile(tile), tile);
if (callback_res != CALLBACK_FAILED && callback_res != 0x400) {
if (callback_res > 0x400) {
ErrorUnknownCallbackResult(hs->grf_prop.grffile->grfid, CBID_HOUSE_CUSTOM_NAME, callback_res);
} else {
StringID new_name = GetGRFStringID(hs->grf_prop.grffile->grfid, 0xD000 + callback_res);
if (new_name != STR_NULL && new_name != STR_UNDEFINED) {
td->str = new_name;
}
}
}
if (!house_completed) {
td->dparam = td->str;
td->str = STR_LAI_TOWN_INDUSTRY_DESCRIPTION_UNDER_CONSTRUCTION;
}
if (hs->grf_prop.grffile != nullptr) {
const GRFConfig *gc = GetGRFConfig(hs->grf_prop.grffile->grfid);
td->grf = gc->GetName();
}
td->owner[0] = OWNER_TOWN;
}
static TrackStatus GetTileTrackStatus_Town(TileIndex, TransportType, uint, DiagDirection)
{
/* not used */
return 0;
}
static void ChangeTileOwner_Town(TileIndex, Owner, Owner)
{
/* not used */
}
static bool GrowTown(Town *t);
/**
* Handle the town tick for a single town, by growing the town if desired.
* @param t The town to try growing.
*/
static void TownTickHandler(Town *t)
{
if (HasBit(t->flags, TOWN_IS_GROWING)) {
int i = (int)t->grow_counter - 1;
if (i < 0) {
if (GrowTown(t)) {
i = t->growth_rate;
} else {
/* If growth failed wait a bit before retrying */
i = std::min<uint16_t>(t->growth_rate, Ticks::TOWN_GROWTH_TICKS - 1);
}
}
t->grow_counter = i;
}
}
/** Iterate through all towns and call their tick handler. */
void OnTick_Town()
{
if (_game_mode == GM_EDITOR) return;
for (Town *t : Town::Iterate()) {
TownTickHandler(t);
}
}
/**
* Return the RoadBits of a tile, ignoring depot and bay road stops.
* @param tile The tile to check.
* @return The roadbits of the given tile.
*/
static RoadBits GetTownRoadBits(TileIndex tile)
{
if (IsRoadDepotTile(tile) || IsBayRoadStopTile(tile)) return ROAD_NONE;
return GetAnyRoadBits(tile, RTT_ROAD, true);
}
/**
* Get the road type that towns should build at this current moment.
* They may have built a different type in the past.
*/
RoadType GetTownRoadType()
{
RoadType best_rt = ROADTYPE_ROAD;
const RoadTypeInfo *best = nullptr;
const uint16_t assume_max_speed = 50;
for (RoadType rt = ROADTYPE_BEGIN; rt != ROADTYPE_END; rt++) {
if (RoadTypeIsTram(rt)) continue;
const RoadTypeInfo *rti = GetRoadTypeInfo(rt);
/* Unused road type. */
if (rti->label == 0) continue;
/* Can town build this road. */
if (!HasBit(rti->flags, ROTF_TOWN_BUILD)) continue;
/* Not yet introduced at this date. */
if (IsInsideMM(rti->introduction_date, 0, CalendarTime::MAX_DATE.base()) && rti->introduction_date > TimerGameCalendar::date) continue;
if (best != nullptr) {
if ((rti->max_speed == 0 ? assume_max_speed : rti->max_speed) < (best->max_speed == 0 ? assume_max_speed : best->max_speed)) continue;
}
best_rt = rt;
best = rti;
}
return best_rt;
}
/**
* Check for parallel road inside a given distance.
* Assuming a road from (tile - TileOffsByDiagDir(dir)) to tile,
* is there a parallel road left or right of it within distance dist_multi?
*
* @param tile The current tile.
* @param dir The target direction.
* @param dist_multi The distance multiplier.
* @return true if there is a parallel road.
*/
static bool IsNeighborRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
{
if (!IsValidTile(tile)) return false;
/* Lookup table for the used diff values */
const TileIndexDiff tid_lt[3] = {
TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90RIGHT)),
TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90LEFT)),
TileOffsByDiagDir(ReverseDiagDir(dir)),
};
dist_multi = (dist_multi + 1) * 4;
for (uint pos = 4; pos < dist_multi; pos++) {
/* Go (pos / 4) tiles to the left or the right */
TileIndexDiff cur = tid_lt[(pos & 1) ? 0 : 1] * (pos / 4);
/* Use the current tile as origin, or go one tile backwards */
if (pos & 2) cur += tid_lt[2];
/* Test for roadbit parallel to dir and facing towards the middle axis */
if (IsValidTile(tile + cur) &&
GetTownRoadBits(TileAdd(tile, cur)) & DiagDirToRoadBits((pos & 2) ? dir : ReverseDiagDir(dir))) return true;
}
return false;
}
/**
* Check if a Road is allowed on a given tile.
*
* @param t The current town.
* @param tile The target tile.
* @param dir The direction in which we want to extend the town.
* @return true if it is allowed.
*/
static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
{
if (DistanceFromEdge(tile) == 0) return false;
/* Prevent towns from building roads under bridges along the bridge. Looks silly. */
if (IsBridgeAbove(tile) && GetBridgeAxis(tile) == DiagDirToAxis(dir)) return false;
/* Check if there already is a road at this point? */
if (GetTownRoadBits(tile) == ROAD_NONE) {
/* No, try if we are able to build a road piece there.
* If that fails clear the land, and if that fails exit.
* This is to make sure that we can build a road here later. */
RoadType rt = GetTownRoadType();
if (Command<CMD_BUILD_ROAD>::Do(DC_AUTO | DC_NO_WATER, tile, (dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? ROAD_Y : ROAD_X, rt, DRD_NONE, 0).Failed() &&