OpenTTD Source: src/station_cmd.cpp Source File

OpenTTD Source 15.0-beta1

station_cmd.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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/>.
6 */
7
10#include "stdafx.h"
11#include "aircraft.h"
12#include "bridge_map.h"
13#include "vehiclelist_func.h"
14#include "viewport_func.h"
15#include "viewport_kdtree.h"
16#include "command_func.h"
17#include "town.h"
18#include "news_func.h"
19#include "train.h"
20#include "ship.h"
21#include "roadveh.h"
22#include "industry.h"
23#include "newgrf_cargo.h"
24#include "newgrf_debug.h"
25#include "newgrf_station.h"
26#include "newgrf_canal.h" /* For the buoy */
27#include "pathfinder/yapf/yapf_cache.h"
28#include "road_internal.h" /* For drawing catenary/checking road removal */
29#include "autoslope.h"
30#include "water.h"
31#include "strings_internal.h"
32#include "clear_func.h"
33#include "timer/timer_game_calendar.h"
34#include "vehicle_func.h"
35#include "string_func.h"
36#include "animated_tile_func.h"
37#include "elrail_func.h"
38#include "station_base.h"
39#include "station_func.h"
40#include "station_kdtree.h"
41#include "roadstop_base.h"
42#include "newgrf_railtype.h"
43#include "newgrf_roadtype.h"
44#include "waypoint_base.h"
45#include "waypoint_func.h"
46#include "pbs.h"
47#include "debug.h"
48#include "core/random_func.hpp"
49#include "core/container_func.hpp"
50#include "company_base.h"
51#include "table/airporttile_ids.h"
52#include "newgrf_airporttiles.h"
53#include "order_backup.h"
54#include "newgrf_house.h"
55#include "company_gui.h"
56#include "linkgraph/linkgraph_base.h"
57#include "linkgraph/refresh.h"
58#include "tunnelbridge_map.h"
59#include "station_cmd.h"
60#include "waypoint_cmd.h"
61#include "landscape_cmd.h"
62#include "rail_cmd.h"
63#include "newgrf_roadstop.h"
64#include "timer/timer.h"
65#include "timer/timer_game_calendar.h"
66#include "timer/timer_game_economy.h"
67#include "timer/timer_game_tick.h"
68#include "cheat_type.h"
69#include "road_func.h"
70
71#include "widgets/station_widget.h"
72
73#include "table/strings.h"
74
75#include <bitset>
76
77#include "safeguards.h"
78
84/* static */ const FlowStat::SharesMap FlowStat::empty_sharesmap;
85
92 bool IsHangar(Tile t)
93{
94 assert(IsTileType(t, MP_STATION));
95
96 /* If the tile isn't an airport there's no chance it's a hangar. */
97 if (!IsAirport(t)) return false;
98
99 const Station *st = Station::GetByTile(t);
100 const AirportSpec *as = st->airport.GetSpec();
101
102 for (const auto &depot : as->depots) {
103 if (st->airport.GetRotatedTileFromOffset(depot.ti) == TileIndex(t)) return true;
104 }
105
106 return false;
107}
108
118template <class T, class F>
119 CommandCost GetStationAround(TileArea ta, StationID closest_station, CompanyID company, T **st, F filter)
120{
121 ta.Expand(1);
122
123 /* check around to see if there are any stations there owned by the company */
124 for (TileIndex tile_cur : ta) {
125 if (IsTileType(tile_cur, MP_STATION)) {
126 StationID t = GetStationIndex(tile_cur);
127 if (!T::IsValidID(t) || T::Get(t)->owner != company || !filter(T::Get(t))) continue;
128 if (closest_station == INVALID_STATION) {
129 closest_station = t;
130 } else if (closest_station != t) {
131 return CommandCost(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
132 }
133 }
134 }
135 *st = (closest_station == INVALID_STATION) ? nullptr : T::Get(closest_station);
136 return CommandCost();
137}
138
144 typedef bool (*CMSAMatcher)(TileIndex tile);
145
152 static int CountMapSquareAround(TileIndex tile, CMSAMatcher cmp)
153{
154 int num = 0;
155
156 for (int dx = -3; dx <= 3; dx++) {
157 for (int dy = -3; dy <= 3; dy++) {
158 TileIndex t = TileAddWrap(tile, dx, dy);
159 if (t != INVALID_TILE && cmp(t)) num++;
160 }
161 }
162
163 return num;
164}
165
171 static bool CMSAMine(TileIndex tile)
172{
173 /* No industry */
174 if (!IsTileType(tile, MP_INDUSTRY)) return false;
175
176 const Industry *ind = Industry::GetByTile(tile);
177
178 /* No extractive industry */
179 if ((GetIndustrySpec(ind->type)->life_type & INDUSTRYLIFE_EXTRACTIVE) == 0) return false;
180
181 for (const auto &p : ind->produced) {
182 /* The industry extracts something non-liquid, i.e. no oil or plastic, so it is a mine.
183 * Also the production of passengers and mail is ignored. */
184 if (IsValidCargoID(p.cargo) &&
185 (CargoSpec::Get(p.cargo)->classes & (CC_LIQUID | CC_PASSENGERS | CC_MAIL)) == 0) {
186 return true;
187 }
188 }
189
190 return false;
191}
192
198 static bool CMSAWater(TileIndex tile)
199{
200 return IsTileType(tile, MP_WATER) && IsWater(tile);
201}
202
208 static bool CMSATree(TileIndex tile)
209{
210 return IsTileType(tile, MP_TREES);
211}
212
213#define M(x) ((x) - STR_SV_STNAME)
214
215enum StationNaming {
216 STATIONNAMING_RAIL,
217 STATIONNAMING_ROAD,
218 STATIONNAMING_AIRPORT,
219 STATIONNAMING_OILRIG,
220 STATIONNAMING_DOCK,
221 STATIONNAMING_HELIPORT,
222};
223
225 struct StationNameInformation {
226 uint32_t free_names;
227 std::bitset<NUM_INDUSTRYTYPES> indtypes;
228};
229
238 static bool FindNearIndustryName(TileIndex tile, void *user_data)
239{
240 /* All already found industry types */
241 StationNameInformation *sni = (StationNameInformation*)user_data;
242 if (!IsTileType(tile, MP_INDUSTRY)) return false;
243
244 /* If the station name is undefined it means that it doesn't name a station */
245 IndustryType indtype = GetIndustryType(tile);
246 if (GetIndustrySpec(indtype)->station_name == STR_UNDEFINED) return false;
247
248 /* In all cases if an industry that provides a name is found two of
249 * the standard names will be disabled. */
250 sni->free_names &= ~(1 << M(STR_SV_STNAME_OILFIELD) | 1 << M(STR_SV_STNAME_MINES));
251 return !sni->indtypes[indtype];
252}
253
254 static StringID GenerateStationName(Station *st, TileIndex tile, StationNaming name_class)
255{
256 static const uint32_t _gen_station_name_bits[] = {
257 0, // STATIONNAMING_RAIL
258 0, // STATIONNAMING_ROAD
259 1U << M(STR_SV_STNAME_AIRPORT), // STATIONNAMING_AIRPORT
260 1U << M(STR_SV_STNAME_OILFIELD), // STATIONNAMING_OILRIG
261 1U << M(STR_SV_STNAME_DOCKS), // STATIONNAMING_DOCK
262 1U << M(STR_SV_STNAME_HELIPORT), // STATIONNAMING_HELIPORT
263 };
264
265 const Town *t = st->town;
266
267 StationNameInformation sni{};
268 sni.free_names = UINT32_MAX;
269
270 for (const Station *s : Station::Iterate()) {
271 if (s != st && s->town == t) {
272 if (s->indtype != IT_INVALID) {
273 sni.indtypes[s->indtype] = true;
274 StringID name = GetIndustrySpec(s->indtype)->station_name;
275 if (name != STR_UNDEFINED) {
276 /* Filter for other industrytypes with the same name */
277 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
278 const IndustrySpec *indsp = GetIndustrySpec(it);
279 if (indsp->enabled && indsp->station_name == name) sni.indtypes[it] = true;
280 }
281 }
282 continue;
283 }
284 uint str = M(s->string_id);
285 if (str <= 0x20) {
286 if (str == M(STR_SV_STNAME_FOREST)) {
287 str = M(STR_SV_STNAME_WOODS);
288 }
289 ClrBit(sni.free_names, str);
290 }
291 }
292 }
293
294 TileIndex indtile = tile;
295 if (CircularTileSearch(&indtile, 7, FindNearIndustryName, &sni)) {
296 /* An industry has been found nearby */
297 IndustryType indtype = GetIndustryType(indtile);
298 const IndustrySpec *indsp = GetIndustrySpec(indtype);
299 /* STR_NULL means it only disables oil rig/mines */
300 if (indsp->station_name != STR_NULL) {
301 st->indtype = indtype;
302 return STR_SV_STNAME_FALLBACK;
303 }
304 }
305
306 /* Oil rigs/mines name could be marked not free by looking for a near by industry. */
307
308 /* check default names */
309 uint32_t tmp = sni.free_names & _gen_station_name_bits[name_class];
310 if (tmp != 0) return STR_SV_STNAME + FindFirstBit(tmp);
311
312 /* check mine? */
313 if (HasBit(sni.free_names, M(STR_SV_STNAME_MINES))) {
314 if (CountMapSquareAround(tile, CMSAMine) >= 2) {
315 return STR_SV_STNAME_MINES;
316 }
317 }
318
319 /* check close enough to town to get central as name? */
320 if (DistanceMax(tile, t->xy) < 8) {
321 if (HasBit(sni.free_names, M(STR_SV_STNAME))) return STR_SV_STNAME;
322
323 if (HasBit(sni.free_names, M(STR_SV_STNAME_CENTRAL))) return STR_SV_STNAME_CENTRAL;
324 }
325
326 /* Check lakeside */
327 if (HasBit(sni.free_names, M(STR_SV_STNAME_LAKESIDE)) &&
328 DistanceFromEdge(tile) < 20 &&
329 CountMapSquareAround(tile, CMSAWater) >= 5) {
330 return STR_SV_STNAME_LAKESIDE;
331 }
332
333 /* Check woods */
334 if (HasBit(sni.free_names, M(STR_SV_STNAME_WOODS)) && (
335 CountMapSquareAround(tile, CMSATree) >= 8 ||
336 CountMapSquareAround(tile, IsTileForestIndustry) >= 2)
337 ) {
338 return _settings_game.game_creation.landscape == LT_TROPIC ? STR_SV_STNAME_FOREST : STR_SV_STNAME_WOODS;
339 }
340
341 /* check elevation compared to town */
342 int z = GetTileZ(tile);
343 int z2 = GetTileZ(t->xy);
344 if (z < z2) {
345 if (HasBit(sni.free_names, M(STR_SV_STNAME_VALLEY))) return STR_SV_STNAME_VALLEY;
346 } else if (z > z2) {
347 if (HasBit(sni.free_names, M(STR_SV_STNAME_HEIGHTS))) return STR_SV_STNAME_HEIGHTS;
348 }
349
350 /* check direction compared to town */
351 static const int8_t _direction_and_table[] = {
352 ~( (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
353 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
354 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
355 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) ),
356 };
357
358 sni.free_names &= _direction_and_table[
359 (TileX(tile) < TileX(t->xy)) +
360 (TileY(tile) < TileY(t->xy)) * 2];
361
363 static const uint32_t fallback_names = (
364 (1U << M(STR_SV_STNAME_NORTH)) |
365 (1U << M(STR_SV_STNAME_SOUTH)) |
366 (1U << M(STR_SV_STNAME_EAST)) |
367 (1U << M(STR_SV_STNAME_WEST)) |
368 (1U << M(STR_SV_STNAME_TRANSFER)) |
369 (1U << M(STR_SV_STNAME_HALT)) |
370 (1U << M(STR_SV_STNAME_EXCHANGE)) |
371 (1U << M(STR_SV_STNAME_ANNEXE)) |
372 (1U << M(STR_SV_STNAME_SIDINGS)) |
373 (1U << M(STR_SV_STNAME_BRANCH)) |
374 (1U << M(STR_SV_STNAME_UPPER)) |
375 (1U << M(STR_SV_STNAME_LOWER))
376 );
377
378 sni.free_names &= fallback_names;
379 return (sni.free_names == 0) ? STR_SV_STNAME_FALLBACK : (STR_SV_STNAME + FindFirstBit(sni.free_names));
380}
381#undef M
382
388 static Station *GetClosestDeletedStation(TileIndex tile)
389{
390 uint threshold = 8;
391
392 Station *best_station = nullptr;
393 ForAllStationsRadius(tile, threshold, [&](Station *st) {
394 if (!st->IsInUse() && st->owner == _current_company) {
395 uint cur_dist = DistanceManhattan(tile, st->xy);
396
397 if (cur_dist < threshold) {
398 threshold = cur_dist;
399 best_station = st;
400 } else if (cur_dist == threshold && best_station != nullptr) {
401 /* In case of a tie, lowest station ID wins */
402 if (st->index < best_station->index) best_station = st;
403 }
404 }
405 });
406
407 return best_station;
408}
409
410
411 void Station::GetTileArea(TileArea *ta, StationType type) const
412{
413 switch (type) {
414 case STATION_RAIL:
415 *ta = this->train_station;
416 return;
417
418 case STATION_AIRPORT:
419 *ta = this->airport;
420 return;
421
422 case STATION_TRUCK:
423 *ta = this->truck_station;
424 return;
425
426 case STATION_BUS:
427 *ta = this->bus_station;
428 return;
429
430 case STATION_DOCK:
431 case STATION_OILRIG:
432 *ta = this->docking_station;
433 return;
434
435 default: NOT_REACHED();
436 }
437}
438
442 void Station::UpdateVirtCoord()
443{
444 Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
445
446 pt.y -= 32 * ZOOM_BASE;
447 if ((this->facilities & FACIL_AIRPORT) && this->airport.type == AT_OILRIG) pt.y -= 16 * ZOOM_BASE;
448
449 if (this->sign.kdtree_valid) _viewport_sign_kdtree.Remove(ViewportSignKdtreeItem::MakeStation(this->index));
450
451 SetDParam(0, this->index);
452 SetDParam(1, this->facilities);
453 this->sign.UpdatePosition(pt.x, pt.y, STR_VIEWPORT_STATION, STR_VIEWPORT_STATION_TINY);
454
455 _viewport_sign_kdtree.Insert(ViewportSignKdtreeItem::MakeStation(this->index));
456
457 SetWindowDirty(WC_STATION_VIEW, this->index);
458}
459
464 void Station::MoveSign(TileIndex new_xy)
465{
466 if (this->xy == new_xy) return;
467
468 _station_kdtree.Remove(this->index);
469
470 this->BaseStation::MoveSign(new_xy);
471
472 _station_kdtree.Insert(this->index);
473}
474
476 void UpdateAllStationVirtCoords()
477{
478 for (BaseStation *st : BaseStation::Iterate()) {
479 st->UpdateVirtCoord();
480 }
481}
482
483void BaseStation::FillCachedName() const
484{
485 auto tmp_params = MakeParameters(this->index);
486 this->cached_name = GetStringWithArgs(Waypoint::IsExpected(this) ? STR_WAYPOINT_NAME : STR_STATION_NAME, tmp_params);
487}
488
489void ClearAllStationCachedNames()
490{
491 for (BaseStation *st : BaseStation::Iterate()) {
492 st->cached_name.clear();
493 }
494}
495
501CargoTypes GetAcceptanceMask(const Station *st)
502{
503 CargoTypes mask = 0;
504
505 for (auto it = std::begin(st->goods); it != std::end(st->goods); ++it) {
506 if (HasBit(it->status, GoodsEntry::GES_ACCEPTANCE)) SetBit(mask, std::distance(std::begin(st->goods), it));
507 }
508 return mask;
509}
510
516CargoTypes GetEmptyMask(const Station *st)
517{
518 CargoTypes mask = 0;
519
520 for (auto it = std::begin(st->goods); it != std::end(st->goods); ++it) {
521 if (it->cargo.TotalCount() == 0) SetBit(mask, std::distance(std::begin(st->goods), it));
522 }
523 return mask;
524}
525
532 static void ShowRejectOrAcceptNews(const Station *st, CargoTypes cargoes, bool reject)
533{
534 SetDParam(0, st->index);
535 SetDParam(1, cargoes);
536 StringID msg = reject ? STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO_LIST : STR_NEWS_STATION_NOW_ACCEPTS_CARGO_LIST;
537 AddNewsItem(msg, NT_ACCEPTANCE, NF_INCOLOUR | NF_SMALL, NR_STATION, st->index);
538}
539
547 CargoArray GetProductionAroundTiles(TileIndex north_tile, int w, int h, int rad)
548{
549 CargoArray produced{};
550 std::set<IndustryID> industries;
551 TileArea ta = TileArea(north_tile, w, h).Expand(rad);
552
553 /* Loop over all tiles to get the produced cargo of
554 * everything except industries */
555 for (TileIndex tile : ta) {
556 if (IsTileType(tile, MP_INDUSTRY)) industries.insert(GetIndustryIndex(tile));
557 AddProducedCargo(tile, produced);
558 }
559
560 /* Loop over the seen industries. They produce cargo for
561 * anything that is within 'rad' of any one of their tiles.
562 */
563 for (IndustryID industry : industries) {
564 const Industry *i = Industry::Get(industry);
565 /* Skip industry with neutral station */
566 if (i->neutral_station != nullptr && !_settings_game.station.serve_neutral_industries) continue;
567
568 for (const auto &p : i->produced) {
569 if (IsValidCargoID(p.cargo)) produced[p.cargo]++;
570 }
571 }
572
573 return produced;
574}
575
585 CargoArray GetAcceptanceAroundTiles(TileIndex center_tile, int w, int h, int rad, CargoTypes *always_accepted)
586{
587 CargoArray acceptance{};
588 if (always_accepted != nullptr) *always_accepted = 0;
589
590 TileArea ta = TileArea(center_tile, w, h).Expand(rad);
591
592 for (TileIndex tile : ta) {
593 /* Ignore industry if it has a neutral station. */
594 if (!_settings_game.station.serve_neutral_industries && IsTileType(tile, MP_INDUSTRY) && Industry::GetByTile(tile)->neutral_station != nullptr) continue;
595
596 AddAcceptedCargo(tile, acceptance, always_accepted);
597 }
598
599 return acceptance;
600}
601
607 static CargoArray GetAcceptanceAroundStation(const Station *st, CargoTypes *always_accepted)
608{
609 CargoArray acceptance{};
610 if (always_accepted != nullptr) *always_accepted = 0;
611
612 BitmapTileIterator it(st->catchment_tiles);
613 for (TileIndex tile = it; tile != INVALID_TILE; tile = ++it) {
614 AddAcceptedCargo(tile, acceptance, always_accepted);
615 }
616
617 return acceptance;
618}
619
625 void UpdateStationAcceptance(Station *st, bool show_msg)
626{
627 /* old accepted goods types */
628 CargoTypes old_acc = GetAcceptanceMask(st);
629
630 /* And retrieve the acceptance. */
631 CargoArray acceptance{};
632 if (!st->rect.IsEmpty()) {
633 acceptance = GetAcceptanceAroundStation(st, &st->always_accepted);
634 }
635
636 /* Adjust in case our station only accepts fewer kinds of goods */
637 for (CargoID i = 0; i < NUM_CARGO; i++) {
638 uint amt = acceptance[i];
639
640 /* Make sure the station can accept the goods type. */
641 bool is_passengers = IsCargoInClass(i, CC_PASSENGERS);
642 if ((!is_passengers && !(st->facilities & ~FACIL_BUS_STOP)) ||
643 (is_passengers && !(st->facilities & ~FACIL_TRUCK_STOP))) {
644 amt = 0;
645 }
646
647 GoodsEntry &ge = st->goods[i];
648 SB(ge.status, GoodsEntry::GES_ACCEPTANCE, 1, amt >= 8);
649 if (LinkGraph::IsValidID(ge.link_graph)) {
650 (*LinkGraph::Get(ge.link_graph))[ge.node].SetDemand(amt / 8);
651 }
652 }
653
654 /* Only show a message in case the acceptance was actually changed. */
655 CargoTypes new_acc = GetAcceptanceMask(st);
656 if (old_acc == new_acc) return;
657
658 /* show a message to report that the acceptance was changed? */
659 if (show_msg && st->owner == _local_company && st->IsInUse()) {
660 /* Combine old and new masks to get changes */
661 CargoTypes accepts = new_acc & ~old_acc;
662 CargoTypes rejects = ~new_acc & old_acc;
663
664 /* Show news message if there are any changes */
665 if (accepts != 0) ShowRejectOrAcceptNews(st, accepts, false);
666 if (rejects != 0) ShowRejectOrAcceptNews(st, rejects, true);
667 }
668
669 /* redraw the station view since acceptance changed */
670 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ACCEPT_RATING_LIST);
671}
672
673static void UpdateStationSignCoord(BaseStation *st)
674{
675 const StationRect *r = &st->rect;
676
677 if (r->IsEmpty()) return; // no tiles belong to this station
678
679 /* clamp sign coord to be inside the station rect */
680 TileIndex new_xy = TileXY(ClampU(TileX(st->xy), r->left, r->right), ClampU(TileY(st->xy), r->top, r->bottom));
681 st->MoveSign(new_xy);
682
683 if (!Station::IsExpected(st)) return;
684 Station *full_station = Station::From(st);
685 for (const GoodsEntry &ge : full_station->goods) {
686 LinkGraphID lg = ge.link_graph;
687 if (!LinkGraph::IsValidID(lg)) continue;
688 (*LinkGraph::Get(lg))[ge.node].UpdateLocation(st->xy);
689 }
690}
691
701 static CommandCost BuildStationPart(Station **st, DoCommandFlag flags, bool reuse, TileArea area, StationNaming name_class)
702{
703 /* Find a deleted station close to us */
704 if (*st == nullptr && reuse) *st = GetClosestDeletedStation(area.tile);
705
706 if (*st != nullptr) {
707 if ((*st)->owner != _current_company) {
708 return CommandCost(CMD_ERROR);
709 }
710
711 CommandCost ret = (*st)->rect.BeforeAddRect(area.tile, area.w, area.h, StationRect::ADD_TEST);
712 if (ret.Failed()) return ret;
713 } else {
714 /* allocate and initialize new station */
715 if (!Station::CanAllocateItem()) return CommandCost(STR_ERROR_TOO_MANY_STATIONS_LOADING);
716
717 if (flags & DC_EXEC) {
718 *st = new Station(area.tile);
719 _station_kdtree.Insert((*st)->index);
720
721 (*st)->town = ClosestTownFromTile(area.tile, UINT_MAX);
722 (*st)->string_id = GenerateStationName(*st, area.tile, name_class);
723
724 if (Company::IsValidID(_current_company)) {
725 SetBit((*st)->town->have_ratings, _current_company);
726 }
727 }
728 }
729 return CommandCost();
730}
731
738 static void DeleteStationIfEmpty(BaseStation *st)
739{
740 if (!st->IsInUse()) {
741 st->delete_ctr = 0;
742 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
743 }
744 /* station remains but it probably lost some parts - station sign should stay in the station boundaries */
745 UpdateStationSignCoord(st);
746}
747
753 void Station::AfterStationTileSetChange(bool adding, StationType type)
754{
755 this->UpdateVirtCoord();
756 DirtyCompanyInfrastructureWindows(this->owner);
757
758 if (adding) {
759 this->RecomputeCatchment();
760 MarkCatchmentTilesDirty();
761 InvalidateWindowData(WC_STATION_LIST, this->owner, 0);
762 } else {
763 MarkCatchmentTilesDirty();
764 }
765
766 switch (type) {
767 case STATION_RAIL:
768 SetWindowWidgetDirty(WC_STATION_VIEW, this->index, WID_SV_TRAINS);
769 break;
770 case STATION_AIRPORT:
771 break;
772 case STATION_TRUCK:
773 case STATION_BUS:
774 SetWindowWidgetDirty(WC_STATION_VIEW, this->index, WID_SV_ROADVEHS);
775 break;
776 case STATION_DOCK:
777 SetWindowWidgetDirty(WC_STATION_VIEW, this->index, WID_SV_SHIPS);
778 break;
779 default: NOT_REACHED();
780 }
781
782 if (adding) {
783 UpdateStationAcceptance(this, false);
784 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
785 } else {
786 DeleteStationIfEmpty(this);
787 this->RecomputeCatchment();
788 }
789
790}
791
792 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags);
793
803 CommandCost CheckBuildableTile(TileIndex tile, uint invalid_dirs, int &allowed_z, bool allow_steep, bool check_bridge = true)
804{
805 if (check_bridge && IsBridgeAbove(tile)) {
806 return CommandCost(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
807 }
808
809 CommandCost ret = EnsureNoVehicleOnGround(tile);
810 if (ret.Failed()) return ret;
811
812 auto [tileh, z] = GetTileSlopeZ(tile);
813
814 /* Prohibit building if
815 * 1) The tile is "steep" (i.e. stretches two height levels).
816 * 2) The tile is non-flat and the build_on_slopes switch is disabled.
817 */
818 if ((!allow_steep && IsSteepSlope(tileh)) ||
819 ((!_settings_game.construction.build_on_slopes) && tileh != SLOPE_FLAT)) {
820 return CommandCost(STR_ERROR_FLAT_LAND_REQUIRED);
821 }
822
823 CommandCost cost(EXPENSES_CONSTRUCTION);
824 int flat_z = z + GetSlopeMaxZ(tileh);
825 if (tileh != SLOPE_FLAT) {
826 /* Forbid building if the tile faces a slope in a invalid direction. */
827 for (DiagDirection dir = DIAGDIR_BEGIN; dir != DIAGDIR_END; dir++) {
828 if (HasBit(invalid_dirs, dir) && !CanBuildDepotByTileh(dir, tileh)) {
829 return CommandCost(STR_ERROR_FLAT_LAND_REQUIRED);
830 }
831 }
832 cost.AddCost(_price[PR_BUILD_FOUNDATION]);
833 }
834
835 /* The level of this tile must be equal to allowed_z. */
836 if (allowed_z < 0) {
837 /* First tile. */
838 allowed_z = flat_z;
839 } else if (allowed_z != flat_z) {
840 return CommandCost(STR_ERROR_FLAT_LAND_REQUIRED);
841 }
842
843 return cost;
844}
845
852 static CommandCost CheckFlatLandAirport(AirportTileTableIterator tile_iter, DoCommandFlag flags)
853{
854 CommandCost cost(EXPENSES_CONSTRUCTION);
855 int allowed_z = -1;
856
857 for (; tile_iter != INVALID_TILE; ++tile_iter) {
858 CommandCost ret = CheckBuildableTile(tile_iter, 0, allowed_z, true);
859 if (ret.Failed()) return ret;
860 cost.AddCost(ret);
861
862 ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile_iter);
863 if (ret.Failed()) return ret;
864 cost.AddCost(ret);
865 }
866
867 return cost;
868}
869
886 static CommandCost CheckFlatLandRailStation(TileIndex tile_cur, TileIndex north_tile, int &allowed_z, DoCommandFlag flags, Axis axis, StationID *station, RailType rt, std::vector<Train *> &affected_vehicles, StationClassID spec_class, uint16_t spec_index, uint8_t plat_len, uint8_t numtracks)
887{
888 CommandCost cost(EXPENSES_CONSTRUCTION);
889 uint invalid_dirs = 5 << axis;
890
891 const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
892 bool slope_cb = statspec != nullptr && HasBit(statspec->callback_mask, CBM_STATION_SLOPE_CHECK);
893
894 CommandCost ret = CheckBuildableTile(tile_cur, invalid_dirs, allowed_z, false);
895 if (ret.Failed()) return ret;
896 cost.AddCost(ret);
897
898 if (slope_cb) {
899 /* Do slope check if requested. */
900 ret = PerformStationTileSlopeCheck(north_tile, tile_cur, statspec, axis, plat_len, numtracks);
901 if (ret.Failed()) return ret;
902 }
903
904 /* if station is set, then we have special handling to allow building on top of already existing stations.
905 * so station points to INVALID_STATION if we can build on any station.
906 * Or it points to a station if we're only allowed to build on exactly that station. */
907 if (station != nullptr && IsTileType(tile_cur, MP_STATION)) {
908 if (!IsRailStation(tile_cur)) {
909 return ClearTile_Station(tile_cur, DC_AUTO); // get error message
910 } else {
911 StationID st = GetStationIndex(tile_cur);
912 if (*station == INVALID_STATION) {
913 *station = st;
914 } else if (*station != st) {
915 return CommandCost(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
916 }
917 }
918 } else {
919 /* If we are building a station with a valid railtype, we may be able to overbuild an existing rail tile. */
920 if (rt != INVALID_RAILTYPE && IsPlainRailTile(tile_cur)) {
921 /* Don't overbuild signals. */
922 if (HasSignals(tile_cur)) return CommandCost(STR_ERROR_MUST_REMOVE_SIGNALS_FIRST);
923
924 /* The current rail type must have power on the to-be-built type (e.g. convert normal rail to electrified rail). */
925 if (HasPowerOnRail(GetRailType(tile_cur), rt)) {
926 TrackBits tracks = GetTrackBits(tile_cur);
927 Track track = RemoveFirstTrack(&tracks);
928 Track expected_track = HasBit(invalid_dirs, DIAGDIR_NE) ? TRACK_X : TRACK_Y;
929
930 /* The existing track must align with the desired station axis. */
931 if (tracks == TRACK_BIT_NONE && track == expected_track) {
932 /* Check for trains having a reservation for this tile. */
933 if (HasBit(GetRailReservationTrackBits(tile_cur), track)) {
934 Train *v = GetTrainForReservation(tile_cur, track);
935 if (v != nullptr) {
936 affected_vehicles.push_back(v);
937 }
938 }
939 ret = Command<CMD_REMOVE_SINGLE_RAIL>::Do(flags, tile_cur, track);
940 if (ret.Failed()) return ret;
941 cost.AddCost(ret);
942 /* With flags & ~DC_EXEC CmdLandscapeClear would fail since the rail still exists */
943 return cost;
944 }
945 }
946 }
947 ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile_cur);
948 if (ret.Failed()) return ret;
949 cost.AddCost(ret);
950 }
951
952 return cost;
953}
954
968 CommandCost CheckFlatLandRoadStop(TileIndex cur_tile, int &allowed_z, DoCommandFlag flags, uint invalid_dirs, bool is_drive_through, StationType station_type, Axis axis, StationID *station, RoadType rt)
969{
970 CommandCost cost(EXPENSES_CONSTRUCTION);
971
972 CommandCost ret = CheckBuildableTile(cur_tile, invalid_dirs, allowed_z, !is_drive_through);
973 if (ret.Failed()) return ret;
974 cost.AddCost(ret);
975
976 /* If station is set, then we have special handling to allow building on top of already existing stations.
977 * Station points to INVALID_STATION if we can build on any station.
978 * Or it points to a station if we're only allowed to build on exactly that station. */
979 if (station != nullptr && IsTileType(cur_tile, MP_STATION)) {
980 if (!IsAnyRoadStop(cur_tile)) {
981 return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
982 } else {
983 if (station_type != GetStationType(cur_tile) ||
984 is_drive_through != IsDriveThroughStopTile(cur_tile)) {
985 return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
986 }
987 /* Drive-through station in the wrong direction. */
988 if (is_drive_through && IsDriveThroughStopTile(cur_tile) && GetDriveThroughStopAxis(cur_tile) != axis) {
989 return CommandCost(STR_ERROR_DRIVE_THROUGH_DIRECTION);
990 }
991 StationID st = GetStationIndex(cur_tile);
992 if (*station == INVALID_STATION) {
993 *station = st;
994 } else if (*station != st) {
995 return CommandCost(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
996 }
997 }
998 } else {
999 bool build_over_road = is_drive_through && IsNormalRoadTile(cur_tile);
1000 /* Road bits in the wrong direction. */
1001 RoadBits rb = IsNormalRoadTile(cur_tile) ? GetAllRoadBits(cur_tile) : ROAD_NONE;
1002 if (build_over_road && (rb & (axis == AXIS_X ? ROAD_Y : ROAD_X)) != 0) {
1003 /* Someone was pedantic and *NEEDED* three fracking different error messages. */
1004 switch (CountBits(rb)) {
1005 case 1:
1006 return CommandCost(STR_ERROR_DRIVE_THROUGH_DIRECTION);
1007
1008 case 2:
1009 if (rb == ROAD_X || rb == ROAD_Y) return CommandCost(STR_ERROR_DRIVE_THROUGH_DIRECTION);
1010 return CommandCost(STR_ERROR_DRIVE_THROUGH_CORNER);
1011
1012 default: // 3 or 4
1013 return CommandCost(STR_ERROR_DRIVE_THROUGH_JUNCTION);
1014 }
1015 }
1016
1017 if (build_over_road) {
1018 /* There is a road, check if we can build road+tram stop over it. */
1019 RoadType road_rt = GetRoadType(cur_tile, RTT_ROAD);
1020 if (road_rt != INVALID_ROADTYPE) {
1021 Owner road_owner = GetRoadOwner(cur_tile, RTT_ROAD);
1022 if (road_owner == OWNER_TOWN) {
1023 if (!_settings_game.construction.road_stop_on_town_road) return CommandCost(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD);
1024 } else if (!_settings_game.construction.road_stop_on_competitor_road && road_owner != OWNER_NONE) {
1025 ret = CheckOwnership(road_owner);
1026 if (ret.Failed()) return ret;
1027 }
1028 uint num_pieces = CountBits(GetRoadBits(cur_tile, RTT_ROAD));
1029
1030 if (rt != INVALID_ROADTYPE && RoadTypeIsRoad(rt) && !HasPowerOnRoad(rt, road_rt)) return CommandCost(STR_ERROR_NO_SUITABLE_ROAD);
1031
1032 if (GetDisallowedRoadDirections(cur_tile) != DRD_NONE && road_owner != OWNER_TOWN) {
1033 ret = CheckOwnership(road_owner);
1034 if (ret.Failed()) return ret;
1035 }
1036
1037 cost.AddCost(RoadBuildCost(road_rt) * (2 - num_pieces));
1038 } else if (rt != INVALID_ROADTYPE && RoadTypeIsRoad(rt)) {
1039 cost.AddCost(RoadBuildCost(rt) * 2);
1040 }
1041
1042 /* There is a tram, check if we can build road+tram stop over it. */
1043 RoadType tram_rt = GetRoadType(cur_tile, RTT_TRAM);
1044 if (tram_rt != INVALID_ROADTYPE) {
1045 Owner tram_owner = GetRoadOwner(cur_tile, RTT_TRAM);
1046 if (Company::IsValidID(tram_owner) &&
1047 (!_settings_game.construction.road_stop_on_competitor_road ||
1048 /* Disallow breaking end-of-line of someone else
1049 * so trams can still reverse on this tile. */
1050 HasExactlyOneBit(GetRoadBits(cur_tile, RTT_TRAM)))) {
1051 ret = CheckOwnership(tram_owner);
1052 if (ret.Failed()) return ret;
1053 }
1054 uint num_pieces = CountBits(GetRoadBits(cur_tile, RTT_TRAM));
1055
1056 if (rt != INVALID_ROADTYPE && RoadTypeIsTram(rt) && !HasPowerOnRoad(rt, tram_rt)) return CommandCost(STR_ERROR_NO_SUITABLE_ROAD);
1057
1058 cost.AddCost(RoadBuildCost(tram_rt) * (2 - num_pieces));
1059 } else if (rt != INVALID_ROADTYPE && RoadTypeIsTram(rt)) {
1060 cost.AddCost(RoadBuildCost(rt) * 2);
1061 }
1062 } else if (rt == INVALID_ROADTYPE) {
1063 return CommandCost(STR_ERROR_THERE_IS_NO_ROAD);
1064 } else {
1065 ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, cur_tile);
1066 if (ret.Failed()) return ret;
1067 cost.AddCost(ret);
1068 cost.AddCost(RoadBuildCost(rt) * 2);
1069 }
1070 }
1071
1072 return cost;
1073}
1074
1081 CommandCost CanExpandRailStation(const BaseStation *st, TileArea &new_ta)
1082{
1083 TileArea cur_ta = st->train_station;
1084
1085 /* determine new size of train station region.. */
1086 int x = std::min(TileX(cur_ta.tile), TileX(new_ta.tile));
1087 int y = std::min(TileY(cur_ta.tile), TileY(new_ta.tile));
1088 new_ta.w = std::max(TileX(cur_ta.tile) + cur_ta.w, TileX(new_ta.tile) + new_ta.w) - x;
1089 new_ta.h = std::max(TileY(cur_ta.tile) + cur_ta.h, TileY(new_ta.tile) + new_ta.h) - y;
1090 new_ta.tile = TileXY(x, y);
1091
1092 /* make sure the final size is not too big. */
1093 if (new_ta.w > _settings_game.station.station_spread || new_ta.h > _settings_game.station.station_spread) {
1094 return CommandCost(STR_ERROR_STATION_TOO_SPREAD_OUT);
1095 }
1096
1097 return CommandCost();
1098}
1099
1100static inline uint8_t *CreateSingle(uint8_t *layout, int n)
1101{
1102 int i = n;
1103 do *layout++ = 0; while (--i);
1104 layout[((n - 1) >> 1) - n] = 2;
1105 return layout;
1106}
1107
1108static inline uint8_t *CreateMulti(uint8_t *layout, int n, uint8_t b)
1109{
1110 int i = n;
1111 do *layout++ = b; while (--i);
1112 if (n > 4) {
1113 layout[0 - n] = 0;
1114 layout[n - 1 - n] = 0;
1115 }
1116 return layout;
1117}
1118
1126 void GetStationLayout(uint8_t *layout, uint numtracks, uint plat_len, const StationSpec *statspec)
1127{
1128 if (statspec != nullptr) {
1129 auto found = statspec->layouts.find(GetStationLayoutKey(numtracks, plat_len));
1130 if (found != std::end(statspec->layouts)) {
1131 /* Custom layout defined, copy to buffer. */
1132 std::copy(std::begin(found->second), std::end(found->second), layout);
1133 return;
1134 }
1135 }
1136
1137 if (plat_len == 1) {
1138 CreateSingle(layout, numtracks);
1139 } else {
1140 if (numtracks & 1) layout = CreateSingle(layout, plat_len);
1141 int n = numtracks >> 1;
1142
1143 while (--n >= 0) {
1144 layout = CreateMulti(layout, plat_len, 4);
1145 layout = CreateMulti(layout, plat_len, 6);
1146 }
1147 }
1148}
1149
1162template <class T, StringID error_message, class F>
1163 CommandCost FindJoiningBaseStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, T **st, F filter)
1164{
1165 assert(*st == nullptr);
1166 bool check_surrounding = true;
1167
1168 if (existing_station != INVALID_STATION) {
1169 if (adjacent && existing_station != station_to_join) {
1170 /* You can't build an adjacent station over the top of one that
1171 * already exists. */
1172 return CommandCost(error_message);
1173 } else {
1174 /* Extend the current station, and don't check whether it will
1175 * be near any other stations. */
1176 T *candidate = T::GetIfValid(existing_station);
1177 if (candidate != nullptr && filter(candidate)) *st = candidate;
1178 check_surrounding = (*st == nullptr);
1179 }
1180 } else {
1181 /* There's no station here. Don't check the tiles surrounding this
1182 * one if the company wanted to build an adjacent station. */
1183 if (adjacent) check_surrounding = false;
1184 }
1185
1186 if (check_surrounding) {
1187 /* Make sure there is no more than one other station around us that is owned by us. */
1188 CommandCost ret = GetStationAround(ta, existing_station, _current_company, st, filter);
1189 if (ret.Failed()) return ret;
1190 }
1191
1192 /* Distant join */
1193 if (*st == nullptr && station_to_join != INVALID_STATION) *st = T::GetIfValid(station_to_join);
1194
1195 return CommandCost();
1196}
1197
1207 static CommandCost FindJoiningStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
1208{
1209 return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_RAILWAY_STATION_FIRST>(existing_station, station_to_join, adjacent, ta, st, [](const Station *) -> bool { return true; });
1210}
1211
1222 CommandCost FindJoiningWaypoint(StationID existing_waypoint, StationID waypoint_to_join, bool adjacent, TileArea ta, Waypoint **wp, bool is_road)
1223{
1224 if (is_road) {
1225 return FindJoiningBaseStation<Waypoint, STR_ERROR_MUST_REMOVE_ROADWAYPOINT_FIRST>(existing_waypoint, waypoint_to_join, adjacent, ta, wp, [](const Waypoint *wp) -> bool { return HasBit(wp->waypoint_flags, WPF_ROAD); });
1226 } else {
1227 return FindJoiningBaseStation<Waypoint, STR_ERROR_MUST_REMOVE_RAILWAYPOINT_FIRST>(existing_waypoint, waypoint_to_join, adjacent, ta, wp, [](const Waypoint *wp) -> bool { return !HasBit(wp->waypoint_flags, WPF_ROAD); });
1228 }
1229}
1230
1235 static void FreeTrainReservation(Train *v)
1236{
1237 FreeTrainTrackReservation(v);
1238 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
1239 v = v->Last();
1240 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), false);
1241}
1242
1247 static void RestoreTrainReservation(Train *v)
1248{
1249 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
1250 TryPathReserve(v, true, true);
1251 v = v->Last();
1252 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
1253}
1254
1269 static CommandCost CalculateRailStationCost(TileArea tile_area, DoCommandFlag flags, Axis axis, StationID *station, RailType rt, std::vector<Train *> &affected_vehicles, StationClassID spec_class, uint16_t spec_index, uint8_t plat_len, uint8_t numtracks)
1270{
1271 CommandCost cost(EXPENSES_CONSTRUCTION);
1272 bool length_price_ready = true;
1273 uint8_t tracknum = 0;
1274 int allowed_z = -1;
1275 for (TileIndex cur_tile : tile_area) {
1276 /* Clear the land below the station. */
1277 CommandCost ret = CheckFlatLandRailStation(cur_tile, tile_area.tile, allowed_z, flags, axis, station, rt, affected_vehicles, spec_class, spec_index, plat_len, numtracks);
1278 if (ret.Failed()) return ret;
1279
1280 /* Only add _price[PR_BUILD_STATION_RAIL_LENGTH] once for each valid plat_len. */
1281 if (tracknum == numtracks) {
1282 length_price_ready = true;
1283 tracknum = 0;
1284 } else {
1285 tracknum++;
1286 }
1287
1288 /* AddCost for new or rotated rail stations. */
1289 if (!IsRailStationTile(cur_tile) || (IsRailStationTile(cur_tile) && GetRailStationAxis(cur_tile) != axis)) {
1290 cost.AddCost(ret);
1291 cost.AddCost(_price[PR_BUILD_STATION_RAIL]);
1292 cost.AddCost(RailBuildCost(rt));
1293
1294 if (length_price_ready) {
1295 cost.AddCost(_price[PR_BUILD_STATION_RAIL_LENGTH]);
1296 length_price_ready = false;
1297 }
1298 }
1299 }
1300
1301 return cost;
1302}
1303
1310 static StationSpec::TileFlags GetStationTileFlags(StationGfx gfx, const StationSpec *statspec)
1311{
1312 /* Default stations do not draw pylons under roofs (gfx >= 4) */
1313 if (statspec == nullptr || gfx >= statspec->tileflags.size()) return gfx < 4 ? StationSpec::TileFlags::Pylons : StationSpec::TileFlags::None;
1314 return statspec->tileflags[gfx];
1315}
1316
1322 void SetRailStationTileFlags(TileIndex tile, const StationSpec *statspec)
1323{
1324 const auto flags = GetStationTileFlags(GetStationGfx(tile), statspec);
1325 SetStationTileBlocked(tile, HasFlag(flags, StationSpec::TileFlags::Blocked));
1326 SetStationTileHavePylons(tile, HasFlag(flags, StationSpec::TileFlags::Pylons));
1327 SetStationTileHaveWires(tile, !HasFlag(flags, StationSpec::TileFlags::NoWires));
1328}
1329
1344 CommandCost CmdBuildRailStation(DoCommandFlag flags, TileIndex tile_org, RailType rt, Axis axis, uint8_t numtracks, uint8_t plat_len, StationClassID spec_class, uint16_t spec_index, StationID station_to_join, bool adjacent)
1345{
1346 /* Does the authority allow this? */
1347 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile_org, flags);
1348 if (ret.Failed()) return ret;
1349
1350 if (!ValParamRailType(rt) || !IsValidAxis(axis)) return CMD_ERROR;
1351
1352 /* Check if the given station class is valid */
1353 if (static_cast<uint>(spec_class) >= StationClass::GetClassCount()) return CMD_ERROR;
1354 const StationClass *cls = StationClass::Get(spec_class);
1355 if (IsWaypointClass(*cls)) return CMD_ERROR;
1356 if (spec_index >= cls->GetSpecCount()) return CMD_ERROR;
1357 if (plat_len == 0 || numtracks == 0) return CMD_ERROR;
1358
1359 int w_org, h_org;
1360 if (axis == AXIS_X) {
1361 w_org = plat_len;
1362 h_org = numtracks;
1363 } else {
1364 h_org = plat_len;
1365 w_org = numtracks;
1366 }
1367
1368 bool reuse = (station_to_join != NEW_STATION);
1369 if (!reuse) station_to_join = INVALID_STATION;
1370 bool distant_join = (station_to_join != INVALID_STATION);
1371
1372 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
1373
1374 if (h_org > _settings_game.station.station_spread || w_org > _settings_game.station.station_spread) return CMD_ERROR;
1375
1376 /* these values are those that will be stored in train_tile and station_platforms */
1377 TileArea new_location(tile_org, w_org, h_org);
1378
1379 /* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
1380 StationID est = INVALID_STATION;
1381 std::vector<Train *> affected_vehicles;
1382 /* Add construction and clearing expenses. */
1383 CommandCost cost = CalculateRailStationCost(new_location, flags, axis, &est, rt, affected_vehicles, spec_class, spec_index, plat_len, numtracks);
1384 if (cost.Failed()) return cost;
1385
1386 Station *st = nullptr;
1387 ret = FindJoiningStation(est, station_to_join, adjacent, new_location, &st);
1388 if (ret.Failed()) return ret;
1389
1390 ret = BuildStationPart(&st, flags, reuse, new_location, STATIONNAMING_RAIL);
1391 if (ret.Failed()) return ret;
1392
1393 if (st != nullptr && st->train_station.tile != INVALID_TILE) {
1394 ret = CanExpandRailStation(st, new_location);
1395 if (ret.Failed()) return ret;
1396 }
1397
1398 /* Check if we can allocate a custom stationspec to this station */
1399 const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
1400 int specindex = AllocateSpecToStation(statspec, st, (flags & DC_EXEC) != 0);
1401 if (specindex == -1) return CommandCost(STR_ERROR_TOO_MANY_STATION_SPECS);
1402
1403 if (statspec != nullptr) {
1404 /* Perform NewStation checks */
1405
1406 /* Check if the station size is permitted */
1407 if (HasBit(statspec->disallowed_platforms, std::min(numtracks - 1, 7))) return CommandCost(STR_ERROR_STATION_DISALLOWED_NUMBER_TRACKS);
1408 if (HasBit(statspec->disallowed_lengths, std::min(plat_len - 1, 7))) return CommandCost(STR_ERROR_STATION_DISALLOWED_LENGTH);
1409
1410 /* Check if the station is buildable */
1411 if (HasBit(statspec->callback_mask, CBM_STATION_AVAIL)) {
1412 uint16_t cb_res = GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, nullptr, INVALID_TILE);
1413 if (cb_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(statspec->grf_prop.grffile, CBID_STATION_AVAILABILITY, cb_res)) return CMD_ERROR;
1414 }
1415 }
1416
1417 if (flags & DC_EXEC) {
1418 st->train_station = new_location;
1419 st->AddFacility(FACIL_TRAIN, new_location.tile);
1420
1421 st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TRY);
1422
1423 if (statspec != nullptr) {
1424 /* Include this station spec's animation trigger bitmask
1425 * in the station's cached copy. */
1426 st->cached_anim_triggers |= statspec->animation.triggers;
1427 }
1428
1429 TileIndexDiff tile_delta = TileOffsByAxis(axis); // offset to go to the next platform tile
1430 TileIndexDiff track_delta = TileOffsByAxis(OtherAxis(axis)); // offset to go to the next track
1431 Track track = AxisToTrack(axis);
1432
1433 std::vector<uint8_t> layouts(numtracks * plat_len);
1434 GetStationLayout(layouts.data(), numtracks, plat_len, statspec);
1435
1436 uint8_t numtracks_orig = numtracks;
1437
1438 Company *c = Company::Get(st->owner);
1439 size_t layout_idx = 0;
1440 TileIndex tile_track = tile_org;
1441 do {
1442 TileIndex tile = tile_track;
1443 int w = plat_len;
1444 do {
1445 uint8_t layout = layouts[layout_idx++];
1446 if (IsRailStationTile(tile) && HasStationReservation(tile)) {
1447 /* Check for trains having a reservation for this tile. */
1448 Train *v = GetTrainForReservation(tile, AxisToTrack(GetRailStationAxis(tile)));
1449 if (v != nullptr) {
1450 affected_vehicles.push_back(v);
1451 FreeTrainReservation(v);
1452 }
1453 }
1454
1455 /* Railtype can change when overbuilding. */
1456 if (IsRailStationTile(tile)) {
1457 if (!IsStationTileBlocked(tile)) c->infrastructure.rail[GetRailType(tile)]--;
1458 c->infrastructure.station--;
1459 }
1460
1461 /* Remove animation if overbuilding */
1462 DeleteAnimatedTile(tile);
1463 uint8_t old_specindex = HasStationTileRail(tile) ? GetCustomStationSpecIndex(tile) : 0;
1464 MakeRailStation(tile, st->owner, st->index, axis, layout & ~1, rt);
1465 /* Free the spec if we overbuild something */
1466 DeallocateSpecFromStation(st, old_specindex);
1467
1468 SetCustomStationSpecIndex(tile, specindex);
1469 SetStationTileRandomBits(tile, GB(Random(), 0, 4));
1470 SetAnimationFrame(tile, 0);
1471
1472 if (statspec != nullptr) {
1473 /* Use a fixed axis for GetPlatformInfo as our platforms / numtracks are always the right way around */
1474 uint32_t platinfo = GetPlatformInfo(AXIS_X, GetStationGfx(tile), plat_len, numtracks_orig, plat_len - w, numtracks_orig - numtracks, false);
1475
1476 /* As the station is not yet completely finished, the station does not yet exist. */
1477 uint16_t callback = GetStationCallback(CBID_STATION_BUILD_TILE_LAYOUT, platinfo, 0, statspec, nullptr, tile);
1478 if (callback != CALLBACK_FAILED) {
1479 if (callback <= UINT8_MAX) {
1480 SetStationGfx(tile, (callback & ~1) + axis);
1481 } else {
1482 ErrorUnknownCallbackResult(statspec->grf_prop.grfid, CBID_STATION_BUILD_TILE_LAYOUT, callback);
1483 }
1484 }
1485
1486 /* Trigger station animation -- after building? */
1487 TriggerStationAnimation(st, tile, SAT_BUILT);
1488 }
1489
1490 SetRailStationTileFlags(tile, statspec);
1491
1492 if (!IsStationTileBlocked(tile)) c->infrastructure.rail[rt]++;
1493 c->infrastructure.station++;
1494
1495 tile += tile_delta;
1496 } while (--w);
1497 AddTrackToSignalBuffer(tile_track, track, _current_company);
1498 YapfNotifyTrackLayoutChange(tile_track, track);
1499 tile_track += track_delta;
1500 } while (--numtracks);
1501
1502 for (uint i = 0; i < affected_vehicles.size(); ++i) {
1503 /* Restore reservations of trains. */
1504 RestoreTrainReservation(affected_vehicles[i]);
1505 }
1506
1507 /* Check whether we need to expand the reservation of trains already on the station. */
1508 TileArea update_reservation_area;
1509 if (axis == AXIS_X) {
1510 update_reservation_area = TileArea(tile_org, 1, numtracks_orig);
1511 } else {
1512 update_reservation_area = TileArea(tile_org, numtracks_orig, 1);
1513 }
1514
1515 for (TileIndex tile : update_reservation_area) {
1516 /* Don't even try to make eye candy parts reserved. */
1517 if (IsStationTileBlocked(tile)) continue;
1518
1519 DiagDirection dir = AxisToDiagDir(axis);
1520 TileIndexDiff tile_offset = TileOffsByDiagDir(dir);
1521 TileIndex platform_begin = tile;
1522 TileIndex platform_end = tile;
1523
1524 /* We can only account for tiles that are reachable from this tile, so ignore primarily blocked tiles while finding the platform begin and end. */
1525 for (TileIndex next_tile = platform_begin - tile_offset; IsCompatibleTrainStationTile(next_tile, platform_begin); next_tile -= tile_offset) {
1526 platform_begin = next_tile;
1527 }
1528 for (TileIndex next_tile = platform_end + tile_offset; IsCompatibleTrainStationTile(next_tile, platform_end); next_tile += tile_offset) {
1529 platform_end = next_tile;
1530 }
1531
1532 /* If there is at least on reservation on the platform, we reserve the whole platform. */
1533 bool reservation = false;
1534 for (TileIndex t = platform_begin; !reservation && t <= platform_end; t += tile_offset) {
1535 reservation = HasStationReservation(t);
1536 }
1537
1538 if (reservation) {
1539 SetRailStationPlatformReservation(platform_begin, dir, true);
1540 }
1541 }
1542
1543 st->MarkTilesDirty(false);
1544 st->AfterStationTileSetChange(true, STATION_RAIL);
1545 }
1546
1547 return cost;
1548}
1549
1550static TileArea MakeStationAreaSmaller(BaseStation *st, TileArea ta, bool (*func)(BaseStation *, TileIndex))
1551{
1552restart:
1553
1554 /* too small? */
1555 if (ta.w != 0 && ta.h != 0) {
1556 /* check the left side, x = constant, y changes */
1557 for (uint i = 0; !func(st, ta.tile + TileDiffXY(0, i));) {
1558 /* the left side is unused? */
1559 if (++i == ta.h) {
1560 ta.tile += TileDiffXY(1, 0);
1561 ta.w--;
1562 goto restart;
1563 }
1564 }
1565
1566 /* check the right side, x = constant, y changes */
1567 for (uint i = 0; !func(st, ta.tile + TileDiffXY(ta.w - 1, i));) {
1568 /* the right side is unused? */
1569 if (++i == ta.h) {
1570 ta.w--;
1571 goto restart;
1572 }
1573 }
1574
1575 /* check the upper side, y = constant, x changes */
1576 for (uint i = 0; !func(st, ta.tile + TileDiffXY(i, 0));) {
1577 /* the left side is unused? */
1578 if (++i == ta.w) {
1579 ta.tile += TileDiffXY(0, 1);
1580 ta.h--;
1581 goto restart;
1582 }
1583 }
1584
1585 /* check the lower side, y = constant, x changes */
1586 for (uint i = 0; !func(st, ta.tile + TileDiffXY(i, ta.h - 1));) {
1587 /* the left side is unused? */
1588 if (++i == ta.w) {
1589 ta.h--;
1590 goto restart;
1591 }
1592 }
1593 } else {
1594 ta.Clear();
1595 }
1596
1597 return ta;
1598}
1599
1600static bool TileBelongsToRailStation(BaseStation *st, TileIndex tile)
1601{
1602 return st->TileBelongsToRailStation(tile);
1603}
1604
1605static void MakeRailStationAreaSmaller(BaseStation *st)
1606{
1607 st->train_station = MakeStationAreaSmaller(st, st->train_station, TileBelongsToRailStation);
1608}
1609
1610static bool TileBelongsToShipStation(BaseStation *st, TileIndex tile)
1611{
1612 return IsDockTile(tile) && GetStationIndex(tile) == st->index;
1613}
1614
1615static void MakeShipStationAreaSmaller(Station *st)
1616{
1617 st->ship_station = MakeStationAreaSmaller(st, st->ship_station, TileBelongsToShipStation);
1618 UpdateStationDockingTiles(st);
1619}
1620
1621static bool TileBelongsToRoadWaypointStation(BaseStation *st, TileIndex tile)
1622{
1623 return IsRoadWaypointTile(tile) && GetStationIndex(tile) == st->index;
1624}
1625
1626void MakeRoadWaypointStationAreaSmaller(BaseStation *st, TileArea &road_waypoint_area)
1627{
1628 road_waypoint_area = MakeStationAreaSmaller(st, road_waypoint_area, TileBelongsToRoadWaypointStation);
1629}
1630
1641template <class T>
1642 CommandCost RemoveFromRailBaseStation(TileArea ta, std::vector<T *> &affected_stations, DoCommandFlag flags, Money removal_cost, bool keep_rail)
1643{
1644 /* Count of the number of tiles removed */
1645 int quantity = 0;
1646 CommandCost total_cost(EXPENSES_CONSTRUCTION);
1647 /* Accumulator for the errors seen during clearing. If no errors happen,
1648 * and the quantity is 0 there is no station. Otherwise it will be one
1649 * of the other error that got accumulated. */
1650 CommandCost error;
1651
1652 /* Do the action for every tile into the area */
1653 for (TileIndex tile : ta) {
1654 /* Make sure the specified tile is a rail station */
1655 if (!HasStationTileRail(tile)) continue;
1656
1657 /* If there is a vehicle on ground, do not allow to remove (flood) the tile */
1658 CommandCost ret = EnsureNoVehicleOnGround(tile);
1659 error.AddCost(ret);
1660 if (ret.Failed()) continue;
1661
1662 /* Check ownership of station */
1663 T *st = T::GetByTile(tile);
1664 if (st == nullptr) continue;
1665
1666 if (_current_company != OWNER_WATER) {
1667 ret = CheckOwnership(st->owner);
1668 error.AddCost(ret);
1669 if (ret.Failed()) continue;
1670 }
1671
1672 /* If we reached here, the tile is valid so increase the quantity of tiles we will remove */
1673 quantity++;
1674
1675 if (keep_rail || IsStationTileBlocked(tile)) {
1676 /* Don't refund the 'steel' of the track when we keep the
1677 * rail, or when the tile didn't have any rail at all. */
1678 total_cost.AddCost(-_price[PR_CLEAR_RAIL]);
1679 }
1680
1681 if (flags & DC_EXEC) {
1682 /* read variables before the station tile is removed */
1683 uint specindex = GetCustomStationSpecIndex(tile);
1684 Track track = GetRailStationTrack(tile);
1685 Owner owner = GetTileOwner(tile);
1686 RailType rt = GetRailType(tile);
1687 Train *v = nullptr;
1688
1689 if (HasStationReservation(tile)) {
1690 v = GetTrainForReservation(tile, track);
1691 if (v != nullptr) FreeTrainReservation(v);
1692 }
1693
1694 bool build_rail = keep_rail && !IsStationTileBlocked(tile);
1695 if (!build_rail && !IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[rt]--;
1696
1697 DoClearSquare(tile);
1698 DeleteNewGRFInspectWindow(GSF_STATIONS, tile.base());
1699 if (build_rail) MakeRailNormal(tile, owner, TrackToTrackBits(track), rt);
1700 Company::Get(owner)->infrastructure.station--;
1701 DirtyCompanyInfrastructureWindows(owner);
1702
1703 st->rect.AfterRemoveTile(st, tile);
1704 AddTrackToSignalBuffer(tile, track, owner);
1705 YapfNotifyTrackLayoutChange(tile, track);
1706
1707 DeallocateSpecFromStation(st, specindex);
1708
1709 include(affected_stations, st);
1710
1711 if (v != nullptr) RestoreTrainReservation(v);
1712 }
1713 }
1714
1715 if (quantity == 0) return error.Failed() ? error : CommandCost(STR_ERROR_THERE_IS_NO_STATION);
1716
1717 for (T *st : affected_stations) {
1718
1719 /* now we need to make the "spanned" area of the railway station smaller
1720 * if we deleted something at the edges.
1721 * we also need to adjust train_tile. */
1722 MakeRailStationAreaSmaller(st);
1723 UpdateStationSignCoord(st);
1724
1725 /* if we deleted the whole station, delete the train facility. */
1726 if (st->train_station.tile == INVALID_TILE) {
1727 st->facilities &= ~FACIL_TRAIN;
1728 SetWindowClassesDirty(WC_VEHICLE_ORDERS);
1729 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
1730 MarkCatchmentTilesDirty();
1731 st->UpdateVirtCoord();
1732 DeleteStationIfEmpty(st);
1733 }
1734 }
1735
1736 total_cost.AddCost(quantity * removal_cost);
1737 return total_cost;
1738}
1739
1749 CommandCost CmdRemoveFromRailStation(DoCommandFlag flags, TileIndex start, TileIndex end, bool keep_rail)
1750{
1751 if (end == 0) end = start;
1752 if (start >= Map::Size() || end >= Map::Size()) return CMD_ERROR;
1753
1754 TileArea ta(start, end);
1755 std::vector<Station *> affected_stations;
1756
1757 CommandCost ret = RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_STATION_RAIL], keep_rail);
1758 if (ret.Failed()) return ret;
1759
1760 /* Do all station specific functions here. */
1761 for (Station *st : affected_stations) {
1762
1763 if (st->train_station.tile == INVALID_TILE) SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
1764 st->MarkTilesDirty(false);
1765 MarkCatchmentTilesDirty();
1766 st->RecomputeCatchment();
1767 }
1768
1769 /* Now apply the rail cost to the number that we deleted */
1770 return ret;
1771}
1772
1782 CommandCost CmdRemoveFromRailWaypoint(DoCommandFlag flags, TileIndex start, TileIndex end, bool keep_rail)
1783{
1784 if (end == 0) end = start;
1785 if (start >= Map::Size() || end >= Map::Size()) return CMD_ERROR;
1786
1787 TileArea ta(start, end);
1788 std::vector<Waypoint *> affected_stations;
1789
1790 return RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_WAYPOINT_RAIL], keep_rail);
1791}
1792
1793
1802template <class T>
1803 CommandCost RemoveRailStation(T *st, DoCommandFlag flags, Money removal_cost)
1804{
1805 /* Current company owns the station? */
1806 if (_current_company != OWNER_WATER) {
1807 CommandCost ret = CheckOwnership(st->owner);
1808 if (ret.Failed()) return ret;
1809 }
1810
1811 /* determine width and height of platforms */
1812 TileArea ta = st->train_station;
1813
1814 assert(ta.w != 0 && ta.h != 0);
1815
1816 CommandCost cost(EXPENSES_CONSTRUCTION);
1817 /* clear all areas of the station */
1818 for (TileIndex tile : ta) {
1819 /* only remove tiles that are actually train station tiles */
1820 if (st->TileBelongsToRailStation(tile)) {
1821 std::vector<T*> affected_stations; // dummy
1822 CommandCost ret = RemoveFromRailBaseStation(TileArea(tile, 1, 1), affected_stations, flags, removal_cost, false);
1823 if (ret.Failed()) return ret;
1824 cost.AddCost(ret);
1825 }
1826 }
1827
1828 return cost;
1829}
1830
1837 static CommandCost RemoveRailStation(TileIndex tile, DoCommandFlag flags)
1838{
1839 /* if there is flooding, remove platforms tile by tile */
1840 if (_current_company == OWNER_WATER) {
1841 return Command<CMD_REMOVE_FROM_RAIL_STATION>::Do(DC_EXEC, tile, 0, false);
1842 }
1843
1844 Station *st = Station::GetByTile(tile);
1845 CommandCost cost = RemoveRailStation(st, flags, _price[PR_CLEAR_STATION_RAIL]);
1846
1847 if (flags & DC_EXEC) st->RecomputeCatchment();
1848
1849 return cost;
1850}
1851
1858 static CommandCost RemoveRailWaypoint(TileIndex tile, DoCommandFlag flags)
1859{
1860 /* if there is flooding, remove waypoints tile by tile */
1861 if (_current_company == OWNER_WATER) {
1862 return Command<CMD_REMOVE_FROM_RAIL_WAYPOINT>::Do(DC_EXEC, tile, 0, false);
1863 }
1864
1865 return RemoveRailStation(Waypoint::GetByTile(tile), flags, _price[PR_CLEAR_WAYPOINT_RAIL]);
1866}
1867
1868
1874 static RoadStop **FindRoadStopSpot(bool truck_station, Station *st)
1875{
1876 RoadStop **primary_stop = (truck_station) ? &st->truck_stops : &st->bus_stops;
1877
1878 if (*primary_stop == nullptr) {
1879 /* we have no roadstop of the type yet, so write a "primary stop" */
1880 return primary_stop;
1881 } else {
1882 /* there are stops already, so append to the end of the list */
1883 RoadStop *stop = *primary_stop;
1884 while (stop->next != nullptr) stop = stop->next;
1885 return &stop->next;
1886 }
1887}
1888
1889static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags, int replacement_spec_index = -1);
1890 CommandCost RemoveRoadWaypointStop(TileIndex tile, DoCommandFlag flags, int replacement_spec_index = -1);
1891
1901 static CommandCost FindJoiningRoadStop(StationID existing_stop, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
1902{
1903 return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST>(existing_stop, station_to_join, adjacent, ta, st, [](const Station *) -> bool { return true; });
1904}
1905
1919 CommandCost CalculateRoadStopCost(TileArea tile_area, DoCommandFlag flags, bool is_drive_through, StationType station_type, Axis axis, DiagDirection ddir, StationID *est, RoadType rt, Money unit_cost)
1920{
1921 uint invalid_dirs = 0;
1922 if (is_drive_through) {
1923 SetBit(invalid_dirs, AxisToDiagDir(axis));
1924 SetBit(invalid_dirs, ReverseDiagDir(AxisToDiagDir(axis)));
1925 } else {
1926 SetBit(invalid_dirs, ddir);
1927 }
1928
1929 /* Check every tile in the area. */
1930 int allowed_z = -1;
1931 CommandCost cost(EXPENSES_CONSTRUCTION);
1932 for (TileIndex cur_tile : tile_area) {
1933 CommandCost ret = CheckFlatLandRoadStop(cur_tile, allowed_z, flags, invalid_dirs, is_drive_through, station_type, axis, est, rt);
1934 if (ret.Failed()) return ret;
1935
1936 bool is_preexisting_roadstop = IsTileType(cur_tile, MP_STATION) && IsAnyRoadStop(cur_tile);
1937
1938 /* Only add costs if a stop doesn't already exist in the location */
1939 if (!is_preexisting_roadstop) {
1940 cost.AddCost(ret);
1941 cost.AddCost(unit_cost);
1942 }
1943 }
1944
1945 return cost;
1946}
1947
1964 CommandCost CmdBuildRoadStop(DoCommandFlag flags, TileIndex tile, uint8_t width, uint8_t length, RoadStopType stop_type, bool is_drive_through,
1965 DiagDirection ddir, RoadType rt, RoadStopClassID spec_class, uint16_t spec_index, StationID station_to_join, bool adjacent)
1966{
1967 if (!ValParamRoadType(rt) || !IsValidDiagDirection(ddir) || stop_type >= ROADSTOP_END) return CMD_ERROR;
1968 bool reuse = (station_to_join != NEW_STATION);
1969 if (!reuse) station_to_join = INVALID_STATION;
1970 bool distant_join = (station_to_join != INVALID_STATION);
1971
1972 /* Check if the given station class is valid */
1973 if (static_cast<uint>(spec_class) >= RoadStopClass::GetClassCount()) return CMD_ERROR;
1974 const RoadStopClass *cls = RoadStopClass::Get(spec_class);
1975 if (IsWaypointClass(*cls)) return CMD_ERROR;
1976 if (spec_index >= cls->GetSpecCount()) return CMD_ERROR;
1977
1978 const RoadStopSpec *roadstopspec = cls->GetSpec(spec_index);
1979 if (roadstopspec != nullptr) {
1980 if (stop_type == ROADSTOP_TRUCK && roadstopspec->stop_type != ROADSTOPTYPE_FREIGHT && roadstopspec->stop_type != ROADSTOPTYPE_ALL) return CMD_ERROR;
1981 if (stop_type == ROADSTOP_BUS && roadstopspec->stop_type != ROADSTOPTYPE_PASSENGER && roadstopspec->stop_type != ROADSTOPTYPE_ALL) return CMD_ERROR;
1982 if (!is_drive_through && HasBit(roadstopspec->flags, RSF_DRIVE_THROUGH_ONLY)) return CMD_ERROR;
1983 }
1984
1985 /* Check if the requested road stop is too big */
1986 if (width > _settings_game.station.station_spread || length > _settings_game.station.station_spread) return CommandCost(STR_ERROR_STATION_TOO_SPREAD_OUT);
1987 /* Check for incorrect width / length. */
1988 if (width == 0 || length == 0) return CMD_ERROR;
1989 /* Check if the first tile and the last tile are valid */
1990 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, length - 1) == INVALID_TILE) return CMD_ERROR;
1991
1992 TileArea roadstop_area(tile, width, length);
1993
1994 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
1995
1996 /* Trams only have drive through stops */
1997 if (!is_drive_through && RoadTypeIsTram(rt)) return CMD_ERROR;
1998
1999 Axis axis = DiagDirToAxis(ddir);
2000
2001 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
2002 if (ret.Failed()) return ret;
2003
2004 bool is_truck_stop = stop_type != ROADSTOP_BUS;
2005
2006 /* Total road stop cost. */
2007 Money unit_cost;
2008 if (roadstopspec != nullptr) {
2009 unit_cost = roadstopspec->GetBuildCost(is_truck_stop ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS);
2010 } else {
2011 unit_cost = _price[is_truck_stop ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS];
2012 }
2013 StationID est = INVALID_STATION;
2014 CommandCost cost = CalculateRoadStopCost(roadstop_area, flags, is_drive_through, is_truck_stop ? STATION_TRUCK : STATION_BUS, axis, ddir, &est, rt, unit_cost);
2015 if (cost.Failed()) return cost;
2016
2017 Station *st = nullptr;
2018 ret = FindJoiningRoadStop(est, station_to_join, adjacent, roadstop_area, &st);
2019 if (ret.Failed()) return ret;
2020
2021 /* Check if this number of road stops can be allocated. */
2022 if (!RoadStop::CanAllocateItem(static_cast<size_t>(roadstop_area.w) * roadstop_area.h)) return CommandCost(is_truck_stop ? STR_ERROR_TOO_MANY_TRUCK_STOPS : STR_ERROR_TOO_MANY_BUS_STOPS);
2023
2024 ret = BuildStationPart(&st, flags, reuse, roadstop_area, STATIONNAMING_ROAD);
2025 if (ret.Failed()) return ret;
2026
2027 /* Check if we can allocate a custom stationspec to this station */
2028 int specindex = AllocateSpecToRoadStop(roadstopspec, st, (flags & DC_EXEC) != 0);
2029 if (specindex == -1) return CommandCost(STR_ERROR_TOO_MANY_STATION_SPECS);
2030
2031 if (roadstopspec != nullptr) {
2032 /* Perform NewGRF checks */
2033
2034 /* Check if the road stop is buildable */
2035 if (HasBit(roadstopspec->callback_mask, CBM_ROAD_STOP_AVAIL)) {
2036 uint16_t cb_res = GetRoadStopCallback(CBID_STATION_AVAILABILITY, 0, 0, roadstopspec, nullptr, INVALID_TILE, rt, is_truck_stop ? STATION_TRUCK : STATION_BUS, 0);
2037 if (cb_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(roadstopspec->grf_prop.grffile, CBID_STATION_AVAILABILITY, cb_res)) return CMD_ERROR;
2038 }
2039 }
2040
2041 if (flags & DC_EXEC) {
2042 /* Check every tile in the area. */
2043 for (TileIndex cur_tile : roadstop_area) {
2044 /* Get existing road types and owners before any tile clearing */
2045 RoadType road_rt = MayHaveRoad(cur_tile) ? GetRoadType(cur_tile, RTT_ROAD) : INVALID_ROADTYPE;
2046 RoadType tram_rt = MayHaveRoad(cur_tile) ? GetRoadType(cur_tile, RTT_TRAM) : INVALID_ROADTYPE;
2047 Owner road_owner = road_rt != INVALID_ROADTYPE ? GetRoadOwner(cur_tile, RTT_ROAD) : _current_company;
2048 Owner tram_owner = tram_rt != INVALID_ROADTYPE ? GetRoadOwner(cur_tile, RTT_TRAM) : _current_company;
2049
2050 if (IsTileType(cur_tile, MP_STATION) && IsStationRoadStop(cur_tile)) {
2051 RemoveRoadStop(cur_tile, flags, specindex);
2052 }
2053
2054 if (roadstopspec != nullptr) {
2055 /* Include this road stop spec's animation trigger bitmask
2056 * in the station's cached copy. */
2057 st->cached_roadstop_anim_triggers |= roadstopspec->animation.triggers;
2058 }
2059
2060 RoadStop *road_stop = new RoadStop(cur_tile);
2061 /* Insert into linked list of RoadStops. */
2062 RoadStop **currstop = FindRoadStopSpot(is_truck_stop, st);
2063 *currstop = road_stop;
2064
2065 if (is_truck_stop) {
2066 st->truck_station.Add(cur_tile);
2067 } else {
2068 st->bus_station.Add(cur_tile);
2069 }
2070
2071 /* Initialize an empty station. */
2072 st->AddFacility(is_truck_stop ? FACIL_TRUCK_STOP : FACIL_BUS_STOP, cur_tile);
2073
2074 st->rect.BeforeAddTile(cur_tile, StationRect::ADD_TRY);
2075
2076 RoadStopType rs_type = is_truck_stop ? ROADSTOP_TRUCK : ROADSTOP_BUS;
2077 if (is_drive_through) {
2078 /* Update company infrastructure counts. If the current tile is a normal road tile, remove the old
2079 * bits first. */
2080 if (IsNormalRoadTile(cur_tile)) {
2081 UpdateCompanyRoadInfrastructure(road_rt, road_owner, -(int)CountBits(GetRoadBits(cur_tile, RTT_ROAD)));
2082 UpdateCompanyRoadInfrastructure(tram_rt, tram_owner, -(int)CountBits(GetRoadBits(cur_tile, RTT_TRAM)));
2083 }
2084
2085 if (road_rt == INVALID_ROADTYPE && RoadTypeIsRoad(rt)) road_rt = rt;
2086 if (tram_rt == INVALID_ROADTYPE && RoadTypeIsTram(rt)) tram_rt = rt;
2087
2088 MakeDriveThroughRoadStop(cur_tile, st->owner, road_owner, tram_owner, st->index, (rs_type == ROADSTOP_BUS ? STATION_BUS : STATION_TRUCK), road_rt, tram_rt, axis);
2089 road_stop->MakeDriveThrough();
2090 } else {
2091 if (road_rt == INVALID_ROADTYPE && RoadTypeIsRoad(rt)) road_rt = rt;
2092 if (tram_rt == INVALID_ROADTYPE && RoadTypeIsTram(rt)) tram_rt = rt;
2093 MakeRoadStop(cur_tile, st->owner, st->index, rs_type, road_rt, tram_rt, ddir);
2094 }
2095 UpdateCompanyRoadInfrastructure(road_rt, road_owner, ROAD_STOP_TRACKBIT_FACTOR);
2096 UpdateCompanyRoadInfrastructure(tram_rt, tram_owner, ROAD_STOP_TRACKBIT_FACTOR);
2097 Company::Get(st->owner)->infrastructure.station++;
2098
2099 SetCustomRoadStopSpecIndex(cur_tile, specindex);
2100 if (roadstopspec != nullptr) {
2101 st->SetRoadStopRandomBits(cur_tile, GB(Random(), 0, 8));
2102 TriggerRoadStopAnimation(st, cur_tile, SAT_BUILT);
2103 }
2104
2105 MarkTileDirtyByTile(cur_tile);
2106 }
2107
2108 if (st != nullptr) {
2109 st->AfterStationTileSetChange(true, is_truck_stop ? STATION_TRUCK: STATION_BUS);
2110 }
2111 }
2112 return cost;
2113}
2114
2115
2116static Vehicle *ClearRoadStopStatusEnum(Vehicle *v, void *)
2117{
2118 if (v->type == VEH_ROAD) {
2119 /* Okay... we are a road vehicle on a drive through road stop.
2120 * But that road stop has just been removed, so we need to make
2121 * sure we are in a valid state... however, vehicles can also
2122 * turn on road stop tiles, so only clear the 'road stop' state
2123 * bits and only when the state was 'in road stop', otherwise
2124 * we'll end up clearing the turn around bits. */
2125 RoadVehicle *rv = RoadVehicle::From(v);
2126 if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) rv->state &= RVSB_ROAD_STOP_TRACKDIR_MASK;
2127 }
2128
2129 return nullptr;
2130}
2131
2132
2140 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags, int replacement_spec_index)
2141{
2142 Station *st = Station::GetByTile(tile);
2143
2144 if (_current_company != OWNER_WATER) {
2145 CommandCost ret = CheckOwnership(st->owner);
2146 if (ret.Failed()) return ret;
2147 }
2148
2149 bool is_truck = IsTruckStop(tile);
2150
2151 RoadStop **primary_stop;
2152 RoadStop *cur_stop;
2153 if (is_truck) { // truck stop
2154 primary_stop = &st->truck_stops;
2155 cur_stop = RoadStop::GetByTile(tile, ROADSTOP_TRUCK);
2156 } else {
2157 primary_stop = &st->bus_stops;
2158 cur_stop = RoadStop::GetByTile(tile, ROADSTOP_BUS);
2159 }
2160
2161 assert(cur_stop != nullptr);
2162
2163 /* don't do the check for drive-through road stops when company bankrupts */
2164 if (IsDriveThroughStopTile(tile) && (flags & DC_BANKRUPT)) {
2165 /* remove the 'going through road stop' status from all vehicles on that tile */
2166 if (flags & DC_EXEC) FindVehicleOnPos(tile, nullptr, &ClearRoadStopStatusEnum);
2167 } else {
2168 CommandCost ret = EnsureNoVehicleOnGround(tile);
2169 if (ret.Failed()) return ret;
2170 }
2171
2172 const RoadStopSpec *spec = GetRoadStopSpec(tile);
2173
2174 if (flags & DC_EXEC) {
2175 if (*primary_stop == cur_stop) {
2176 /* removed the first stop in the list */
2177 *primary_stop = cur_stop->next;
2178 /* removed the only stop? */
2179 if (*primary_stop == nullptr) {
2180 st->facilities &= (is_truck ? ~FACIL_TRUCK_STOP : ~FACIL_BUS_STOP);
2181 SetWindowClassesDirty(WC_VEHICLE_ORDERS);
2182 }
2183 } else {
2184 /* tell the predecessor in the list to skip this stop */
2185 RoadStop *pred = *primary_stop;
2186 while (pred->next != cur_stop) pred = pred->next;
2187 pred->next = cur_stop->next;
2188 }
2189
2190 /* Update company infrastructure counts. */
2191 for (RoadTramType rtt : _roadtramtypes) {
2192 RoadType rt = GetRoadType(tile, rtt);
2193 UpdateCompanyRoadInfrastructure(rt, GetRoadOwner(tile, rtt), -static_cast<int>(ROAD_STOP_TRACKBIT_FACTOR));
2194 }
2195
2196 Company::Get(st->owner)->infrastructure.station--;
2197 DirtyCompanyInfrastructureWindows(st->owner);
2198
2199 uint specindex = GetCustomRoadStopSpecIndex(tile);
2200
2201 DeleteNewGRFInspectWindow(GSF_ROADSTOPS, tile.base());
2202
2203 if (IsDriveThroughStopTile(tile)) {
2204 /* Clears the tile for us */
2205 cur_stop->ClearDriveThrough();
2206 DeleteAnimatedTile(tile);
2207 } else {
2208 DoClearSquare(tile);
2209 }
2210
2211 delete cur_stop;
2212
2213 /* Make sure no vehicle is going to the old roadstop. Narrow the search to any road vehicles with an order to
2214 * this station, then look for any currently heading to the tile. */
2215 StationID station_id = st->index;
2216 FindVehiclesWithOrder(
2217 [](const Vehicle *v) { return v->type == VEH_ROAD; },
2218 [station_id](const Order *order) { return order->IsType(OT_GOTO_STATION) && order->GetDestination() == station_id; },
2219 [station_id, tile](Vehicle *v) {
2220 if (v->current_order.IsType(OT_GOTO_STATION) && v->dest_tile == tile) {
2221 v->SetDestTile(v->GetOrderStationLocation(station_id));
2222 }
2223 }
2224 );
2225
2226 st->rect.AfterRemoveTile(st, tile);
2227
2228 if (replacement_spec_index < 0) st->AfterStationTileSetChange(false, is_truck ? STATION_TRUCK: STATION_BUS);
2229
2230 st->RemoveRoadStopTileData(tile);
2231 if ((int)specindex != replacement_spec_index) DeallocateSpecFromRoadStop(st, specindex);
2232
2233 /* Update the tile area of the truck/bus stop */
2234 if (is_truck) {
2235 st->truck_station.Clear();
2236 for (const RoadStop *rs = st->truck_stops; rs != nullptr; rs = rs->next) st->truck_station.Add(rs->xy);
2237 } else {
2238 st->bus_station.Clear();
2239 for (const RoadStop *rs = st->bus_stops; rs != nullptr; rs = rs->next) st->bus_station.Add(rs->xy);
2240 }
2241 }
2242
2243 Price category = is_truck ? PR_CLEAR_STATION_TRUCK : PR_CLEAR_STATION_BUS;
2244 return CommandCost(EXPENSES_CONSTRUCTION, spec != nullptr ? spec->GetClearCost(category) : _price[category]);
2245}
2246
2254 CommandCost RemoveRoadWaypointStop(TileIndex tile, DoCommandFlag flags, int replacement_spec_index)
2255{
2256 Waypoint *wp = Waypoint::GetByTile(tile);
2257
2258 if (_current_company != OWNER_WATER) {
2259 CommandCost ret = CheckOwnership(wp->owner);
2260 if (ret.Failed()) return ret;
2261 }
2262
2263 /* Ignore vehicles when the company goes bankrupt. The road will remain, any vehicles going to the waypoint will be removed. */
2264 if (!(flags & DC_BANKRUPT)) {
2265 CommandCost ret = EnsureNoVehicleOnGround(tile);
2266 if (ret.Failed()) return ret;
2267 }
2268
2269 const RoadStopSpec *spec = GetRoadStopSpec(tile);
2270
2271 if (flags & DC_EXEC) {
2272 /* Update company infrastructure counts. */
2273 for (RoadTramType rtt : _roadtramtypes) {
2274 RoadType rt = GetRoadType(tile, rtt);
2275 UpdateCompanyRoadInfrastructure(rt, GetRoadOwner(tile, rtt), -static_cast<int>(ROAD_STOP_TRACKBIT_FACTOR));
2276 }
2277
2278 Company::Get(wp->owner)->infrastructure.station--;
2279 DirtyCompanyInfrastructureWindows(wp->owner);
2280
2281 uint specindex = GetCustomRoadStopSpecIndex(tile);
2282
2283 DeleteNewGRFInspectWindow(GSF_ROADSTOPS, tile.base());
2284
2285 DoClearSquare(tile);
2286
2287 wp->rect.AfterRemoveTile(wp, tile);
2288
2289 wp->RemoveRoadStopTileData(tile);
2290 if ((int)specindex != replacement_spec_index) DeallocateSpecFromRoadStop(wp, specindex);
2291
2292 if (replacement_spec_index < 0) {
2293 MakeRoadWaypointStationAreaSmaller(wp, wp->road_waypoint_area);
2294
2295 UpdateStationSignCoord(wp);
2296
2297 /* if we deleted the whole waypoint, delete the road facility. */
2298 if (wp->road_waypoint_area.tile == INVALID_TILE) {
2299 wp->facilities &= ~(FACIL_BUS_STOP | FACIL_TRUCK_STOP);
2300 SetWindowWidgetDirty(WC_STATION_VIEW, wp->index, WID_SV_ROADVEHS);
2301 wp->UpdateVirtCoord();
2302 DeleteStationIfEmpty(wp);
2303 }
2304 }
2305 }
2306
2307 return CommandCost(EXPENSES_CONSTRUCTION, spec != nullptr ? spec->GetClearCost(PR_CLEAR_STATION_TRUCK) : _price[PR_CLEAR_STATION_TRUCK]);
2308}
2309
2318 static CommandCost RemoveGenericRoadStop(DoCommandFlag flags, const TileArea &roadstop_area, StationType station_type, bool remove_road)
2319{
2320 CommandCost cost(EXPENSES_CONSTRUCTION);
2321 CommandCost last_error(STR_ERROR_THERE_IS_NO_STATION);
2322 bool had_success = false;
2323
2324 for (TileIndex cur_tile : roadstop_area) {
2325 /* Make sure the specified tile is a road stop of the correct type */
2326 if (!IsTileType(cur_tile, MP_STATION) || !IsAnyRoadStop(cur_tile) || GetStationType(cur_tile) != station_type) continue;
2327
2328 /* Save information on to-be-restored roads before the stop is removed. */
2329 RoadBits road_bits = ROAD_NONE;
2330 RoadType road_type[] = { INVALID_ROADTYPE, INVALID_ROADTYPE };
2331 Owner road_owner[] = { OWNER_NONE, OWNER_NONE };
2332 if (IsDriveThroughStopTile(cur_tile)) {
2333 for (RoadTramType rtt : _roadtramtypes) {
2334 road_type[rtt] = GetRoadType(cur_tile, rtt);
2335 if (road_type[rtt] == INVALID_ROADTYPE) continue;
2336 road_owner[rtt] = GetRoadOwner(cur_tile, rtt);
2337 /* If we don't want to preserve our roads then restore only roads of others. */
2338 if (remove_road && road_owner[rtt] == _current_company) road_type[rtt] = INVALID_ROADTYPE;
2339 }
2340 road_bits = AxisToRoadBits(GetDriveThroughStopAxis(cur_tile));
2341 }
2342
2343 CommandCost ret;
2344 if (station_type == STATION_ROADWAYPOINT) {
2345 ret = RemoveRoadWaypointStop(cur_tile, flags);
2346 } else {
2347 ret = RemoveRoadStop(cur_tile, flags);
2348 }
2349 if (ret.Failed()) {
2350 last_error = ret;
2351 continue;
2352 }
2353 cost.AddCost(ret);
2354 had_success = true;
2355
2356 /* Restore roads. */
2357 if ((flags & DC_EXEC) && (road_type[RTT_ROAD] != INVALID_ROADTYPE || road_type[RTT_TRAM] != INVALID_ROADTYPE)) {
2358 MakeRoadNormal(cur_tile, road_bits, road_type[RTT_ROAD], road_type[RTT_TRAM], ClosestTownFromTile(cur_tile, UINT_MAX)->index,
2359 road_owner[RTT_ROAD], road_owner[RTT_TRAM]);
2360
2361 /* Update company infrastructure counts. */
2362 int count = CountBits(road_bits);
2363 UpdateCompanyRoadInfrastructure(road_type[RTT_ROAD], road_owner[RTT_ROAD], count);
2364 UpdateCompanyRoadInfrastructure(road_type[RTT_TRAM], road_owner[RTT_TRAM], count);
2365 }
2366 }
2367
2368 return had_success ? cost : last_error;
2369}
2370
2381 CommandCost CmdRemoveRoadStop(DoCommandFlag flags, TileIndex tile, uint8_t width, uint8_t height, RoadStopType stop_type, bool remove_road)
2382{
2383 if (stop_type >= ROADSTOP_END) return CMD_ERROR;
2384 /* Check for incorrect width / height. */
2385 if (width == 0 || height == 0) return CMD_ERROR;
2386 /* Check if the first tile and the last tile are valid */
2387 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, height - 1) == INVALID_TILE) return CMD_ERROR;
2388 /* Bankrupting company is not supposed to remove roads, there may be road vehicles. */
2389 if (remove_road && (flags & DC_BANKRUPT)) return CMD_ERROR;
2390
2391 TileArea roadstop_area(tile, width, height);
2392
2393 return RemoveGenericRoadStop(flags, roadstop_area, stop_type == ROADSTOP_BUS ? STATION_BUS : STATION_TRUCK, remove_road);
2394}
2395
2403 CommandCost CmdRemoveFromRoadWaypoint(DoCommandFlag flags, TileIndex start, TileIndex end)
2404{
2405 if (end == 0) end = start;
2406 if (start >= Map::Size() || end >= Map::Size()) return CMD_ERROR;
2407
2408 TileArea roadstop_area(start, end);
2409
2410 return RemoveGenericRoadStop(flags, roadstop_area, STATION_ROADWAYPOINT, false);
2411}
2412
2421uint8_t GetAirportNoiseLevelForDistance(const AirportSpec *as, uint distance)
2422{
2423 /* 0 cannot be accounted, and 1 is the lowest that can be reduced from town.
2424 * So no need to go any further*/
2425 if (as->noise_level < 2) return as->noise_level;
2426
2427 /* The steps for measuring noise reduction are based on the "magical" (and arbitrary) 8 base distance
2428 * adding the town_council_tolerance 4 times, as a way to graduate, depending of the tolerance.
2429 * Basically, it says that the less tolerant a town is, the bigger the distance before
2430 * an actual decrease can be granted */
2431 uint8_t town_tolerance_distance = 8 + (_settings_game.difficulty.town_council_tolerance * 4);
2432
2433 /* now, we want to have the distance segmented using the distance judged bareable by town
2434 * This will give us the coefficient of reduction the distance provides. */
2435 uint noise_reduction = distance / town_tolerance_distance;
2436
2437 /* If the noise reduction equals the airport noise itself, don't give it for free.
2438 * Otherwise, simply reduce the airport's level. */
2439 return noise_reduction >= as->noise_level ? 1 : as->noise_level - noise_reduction;
2440}
2441
2452 Town *AirportGetNearestTown(const AirportSpec *as, Direction rotation, TileIndex tile, TileIterator &&it, uint &mindist)
2453{
2454 assert(Town::GetNumItems() > 0);
2455
2456 Town *nearest = nullptr;
2457
2458 auto width = as->size_x;
2459 auto height = as->size_y;
2460 if (rotation == DIR_E || rotation == DIR_W) std::swap(width, height);
2461
2462 uint perimeter_min_x = TileX(tile);
2463 uint perimeter_min_y = TileY(tile);
2464 uint perimeter_max_x = perimeter_min_x + width - 1;
2465 uint perimeter_max_y = perimeter_min_y + height - 1;
2466
2467 mindist = UINT_MAX - 1; // prevent overflow
2468
2469 for (TileIndex cur_tile = *it; cur_tile != INVALID_TILE; cur_tile = ++it) {
2470 assert(IsInsideBS(TileX(cur_tile), perimeter_min_x, width));
2471 assert(IsInsideBS(TileY(cur_tile), perimeter_min_y, height));
2472 if (TileX(cur_tile) == perimeter_min_x || TileX(cur_tile) == perimeter_max_x || TileY(cur_tile) == perimeter_min_y || TileY(cur_tile) == perimeter_max_y) {
2473 Town *t = CalcClosestTownFromTile(cur_tile, mindist + 1);
2474 if (t == nullptr) continue;
2475
2476 uint dist = DistanceManhattan(t->xy, cur_tile);
2477 if (dist == mindist && t->index < nearest->index) nearest = t;
2478 if (dist < mindist) {
2479 nearest = t;
2480 mindist = dist;
2481 }
2482 }
2483 }
2484
2485 return nearest;
2486}
2487
2495 static Town *AirportGetNearestTown(const Station *st, uint &mindist)
2496{
2497 return AirportGetNearestTown(st->airport.GetSpec(), st->airport.rotation, st->airport.tile, AirportTileIterator(st), mindist);
2498}
2499
2500
2502 void UpdateAirportsNoise()
2503{
2504 for (Town *t : Town::Iterate()) t->noise_reached = 0;
2505
2506 for (const Station *st : Station::Iterate()) {
2507 if (st->airport.tile != INVALID_TILE && st->airport.type != AT_OILRIG) {
2508 uint dist;
2509 Town *nearest = AirportGetNearestTown(st, dist);
2510 nearest->noise_reached += GetAirportNoiseLevelForDistance(st->airport.GetSpec(), dist);
2511 }
2512 }
2513}
2514
2525 CommandCost CmdBuildAirport(DoCommandFlag flags, TileIndex tile, uint8_t airport_type, uint8_t layout, StationID station_to_join, bool allow_adjacent)
2526{
2527 bool reuse = (station_to_join != NEW_STATION);
2528 if (!reuse) station_to_join = INVALID_STATION;
2529 bool distant_join = (station_to_join != INVALID_STATION);
2530
2531 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2532
2533 if (airport_type >= NUM_AIRPORTS) return CMD_ERROR;
2534
2535 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
2536 if (ret.Failed()) return ret;
2537
2538 /* Check if a valid, buildable airport was chosen for construction */
2539 const AirportSpec *as = AirportSpec::Get(airport_type);
2540 if (!as->IsAvailable() || layout >= as->layouts.size()) return CMD_ERROR;
2541 if (!as->IsWithinMapBounds(layout, tile)) return CMD_ERROR;
2542
2543 Direction rotation = as->layouts[layout].rotation;
2544 int w = as->size_x;
2545 int h = as->size_y;
2546 if (rotation == DIR_E || rotation == DIR_W) Swap(w, h);
2547 TileArea airport_area = TileArea(tile, w, h);
2548
2549 if (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread) {
2550 return CommandCost(STR_ERROR_STATION_TOO_SPREAD_OUT);
2551 }
2552
2553 AirportTileTableIterator tile_iter(as->layouts[layout].tiles.data(), tile);
2554 CommandCost cost = CheckFlatLandAirport(tile_iter, flags);
2555 if (cost.Failed()) return cost;
2556
2557 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center. */
2558 uint dist;
2559 Town *nearest = AirportGetNearestTown(as, rotation, tile, std::move(tile_iter), dist);
2560 uint newnoise_level = GetAirportNoiseLevelForDistance(as, dist);
2561
2562 /* Check if local auth would allow a new airport */
2563 StringID authority_refuse_message = STR_NULL;
2564 Town *authority_refuse_town = nullptr;
2565
2566 if (_settings_game.economy.station_noise_level) {
2567 /* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
2568 if ((nearest->noise_reached + newnoise_level) > nearest->MaxTownNoise()) {
2569 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE;
2570 authority_refuse_town = nearest;
2571 }
2572 } else if (_settings_game.difficulty.town_council_tolerance != TOWN_COUNCIL_PERMISSIVE) {
2573 Town *t = ClosestTownFromTile(tile, UINT_MAX);
2574 uint num = 0;
2575 for (const Station *st : Station::Iterate()) {
2576 if (st->town == t && (st->facilities & FACIL_AIRPORT) && st->airport.type != AT_OILRIG) num++;
2577 }
2578 if (num >= 2) {
2579 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT;
2580 authority_refuse_town = t;
2581 }
2582 }
2583
2584 if (authority_refuse_message != STR_NULL) {
2585 SetDParam(0, authority_refuse_town->index);
2586 return CommandCost(authority_refuse_message);
2587 }
2588
2589 Station *st = nullptr;
2590 ret = FindJoiningStation(INVALID_STATION, station_to_join, allow_adjacent, airport_area, &st);
2591 if (ret.Failed()) return ret;
2592
2593 /* Distant join */
2594 if (st == nullptr && distant_join) st = Station::GetIfValid(station_to_join);
2595
2596 ret = BuildStationPart(&st, flags, reuse, airport_area, (GetAirport(airport_type)->flags & AirportFTAClass::AIRPLANES) ? STATIONNAMING_AIRPORT : STATIONNAMING_HELIPORT);
2597 if (ret.Failed()) return ret;
2598
2599 if (st != nullptr && st->airport.tile != INVALID_TILE) {
2600 return CommandCost(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT);
2601 }
2602
2603 for (AirportTileTableIterator iter(as->layouts[layout].tiles.data(), tile); iter != INVALID_TILE; ++iter) {
2604 cost.AddCost(_price[PR_BUILD_STATION_AIRPORT]);
2605 }
2606
2607 if (flags & DC_EXEC) {
2608 /* Always add the noise, so there will be no need to recalculate when option toggles */
2609 nearest->noise_reached += newnoise_level;
2610
2611 st->AddFacility(FACIL_AIRPORT, tile);
2612 st->airport.type = airport_type;
2613 st->airport.layout = layout;
2614 st->airport.flags = 0;
2615 st->airport.rotation = rotation;
2616
2617 st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TRY);
2618
2619 for (AirportTileTableIterator iter(as->layouts[layout].tiles.data(), tile); iter != INVALID_TILE; ++iter) {
2620 Tile t(iter);
2621 MakeAirport(t, st->owner, st->index, iter.GetStationGfx(), WATER_CLASS_INVALID);
2622 SetStationTileRandomBits(t, GB(Random(), 0, 4));
2623 st->airport.Add(iter);
2624
2625 if (AirportTileSpec::Get(GetTranslatedAirportTileID(iter.GetStationGfx()))->animation.status != ANIM_STATUS_NO_ANIMATION) AddAnimatedTile(t);
2626 }
2627
2628 /* Only call the animation trigger after all tiles have been built */
2629 for (AirportTileTableIterator iter(as->layouts[layout].tiles.data(), tile); iter != INVALID_TILE; ++iter) {
2630 AirportTileAnimationTrigger(st, iter, AAT_BUILT);
2631 }
2632
2633 UpdateAirplanesOnNewStation(st);
2634
2635 Company::Get(st->owner)->infrastructure.airport++;
2636
2637 st->AfterStationTileSetChange(true, STATION_AIRPORT);
2638 InvalidateWindowData(WC_STATION_VIEW, st->index, -1);
2639
2640 if (_settings_game.economy.station_noise_level) {
2641 SetWindowDirty(WC_TOWN_VIEW, nearest->index);
2642 }
2643 }
2644
2645 return cost;
2646}
2647
2654 static CommandCost RemoveAirport(TileIndex tile, DoCommandFlag flags)
2655{
2656 Station *st = Station::GetByTile(tile);
2657
2658 if (_current_company != OWNER_WATER) {
2659 CommandCost ret = CheckOwnership(st->owner);
2660 if (ret.Failed()) return ret;
2661 }
2662
2663 tile = st->airport.tile;
2664
2665 CommandCost cost(EXPENSES_CONSTRUCTION);
2666
2667 for (const Aircraft *a : Aircraft::Iterate()) {
2668 if (!a->IsNormalAircraft()) continue;
2669 if (a->targetairport == st->index && a->state != FLYING) {
2670 return CommandCost(STR_ERROR_AIRCRAFT_IN_THE_WAY);
2671 }
2672 }
2673
2674 if (flags & DC_EXEC) {
2675 for (uint i = 0; i < st->airport.GetNumHangars(); ++i) {
2676 TileIndex tile_cur = st->airport.GetHangarTile(i);
2677 OrderBackup::Reset(tile_cur, false);
2678 CloseWindowById(WC_VEHICLE_DEPOT, tile_cur);
2679 }
2680
2681 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center.
2682 * And as for construction, always remove it, even if the setting is not set, in order to avoid the
2683 * need of recalculation */
2684 uint dist;
2685 Town *nearest = AirportGetNearestTown(st, dist);
2686 nearest->noise_reached -= GetAirportNoiseLevelForDistance(st->airport.GetSpec(), dist);
2687
2688 if (_settings_game.economy.station_noise_level) {
2689 SetWindowDirty(WC_TOWN_VIEW, nearest->index);
2690 }
2691 }
2692
2693 for (TileIndex tile_cur : st->airport) {
2694 if (!st->TileBelongsToAirport(tile_cur)) continue;
2695
2696 CommandCost ret = EnsureNoVehicleOnGround(tile_cur);
2697 if (ret.Failed()) return ret;
2698
2699 cost.AddCost(_price[PR_CLEAR_STATION_AIRPORT]);
2700
2701 if (flags & DC_EXEC) {
2702 DoClearSquare(tile_cur);
2703 DeleteNewGRFInspectWindow(GSF_AIRPORTTILES, tile_cur.base());
2704 }
2705 }
2706
2707 if (flags & DC_EXEC) {
2708 /* Clear the persistent storage. */
2709 delete st->airport.psa;
2710
2711 st->rect.AfterRemoveRect(st, st->airport);
2712
2713 st->airport.Clear();
2714 st->facilities &= ~FACIL_AIRPORT;
2715 SetWindowClassesDirty(WC_VEHICLE_ORDERS);
2716
2717 InvalidateWindowData(WC_STATION_VIEW, st->index, -1);
2718
2719 Company::Get(st->owner)->infrastructure.airport--;
2720
2721 st->AfterStationTileSetChange(false, STATION_AIRPORT);
2722
2723 DeleteNewGRFInspectWindow(GSF_AIRPORTS, st->index);
2724 }
2725
2726 return cost;
2727}
2728
2735 CommandCost CmdOpenCloseAirport(DoCommandFlag flags, StationID station_id)
2736{
2737 if (!Station::IsValidID(station_id)) return CMD_ERROR;
2738 Station *st = Station::Get(station_id);
2739
2740 if (!(st->facilities & FACIL_AIRPORT) || st->owner == OWNER_NONE) return CMD_ERROR;
2741
2742 CommandCost ret = CheckOwnership(st->owner);
2743 if (ret.Failed()) return ret;
2744
2745 if (flags & DC_EXEC) {
2746 st->airport.flags ^= AIRPORT_CLOSED_block;
2747 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_CLOSE_AIRPORT);
2748 }
2749 return CommandCost();
2750}
2751
2758 bool HasStationInUse(StationID station, bool include_company, CompanyID company)
2759{
2760 for (const OrderList *orderlist : OrderList::Iterate()) {
2761 const Vehicle *v = orderlist->GetFirstSharedVehicle();
2762 assert(v != nullptr);
2763 if ((v->owner == company) != include_company) continue;
2764
2765 for (const Order *order = orderlist->GetFirstOrder(); order != nullptr; order = order->next) {
2766 if (order->GetDestination() == station && (order->IsType(OT_GOTO_STATION) || order->IsType(OT_GOTO_WAYPOINT))) {
2767 return true;
2768 }
2769 }
2770 }
2771 return false;
2772}
2773
2774static const TileIndexDiffC _dock_tileoffs_chkaround[] = {
2775 {-1, 0},
2776 { 0, 0},
2777 { 0, 0},
2778 { 0, -1}
2779};
2780static const uint8_t _dock_w_chk[4] = { 2, 1, 2, 1 };
2781static const uint8_t _dock_h_chk[4] = { 1, 2, 1, 2 };
2782
2791 CommandCost CmdBuildDock(DoCommandFlag flags, TileIndex tile, StationID station_to_join, bool adjacent)
2792{
2793 bool reuse = (station_to_join != NEW_STATION);
2794 if (!reuse) station_to_join = INVALID_STATION;
2795 bool distant_join = (station_to_join != INVALID_STATION);
2796
2797 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2798
2799 DiagDirection direction = GetInclinedSlopeDirection(GetTileSlope(tile));
2800 if (direction == INVALID_DIAGDIR) return CommandCost(STR_ERROR_SITE_UNSUITABLE);
2801 direction = ReverseDiagDir(direction);
2802
2803 /* Docks cannot be placed on rapids */
2804 if (HasTileWaterGround(tile)) return CommandCost(STR_ERROR_SITE_UNSUITABLE);
2805
2806 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
2807 if (ret.Failed()) return ret;
2808
2809 if (IsBridgeAbove(tile)) return CommandCost(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
2810
2811 CommandCost cost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_STATION_DOCK]);
2812 ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile);
2813 if (ret.Failed()) return ret;
2814 cost.AddCost(ret);
2815
2816 TileIndex tile_cur = tile + TileOffsByDiagDir(direction);
2817
2818 if (!HasTileWaterGround(tile_cur) || !IsTileFlat(tile_cur)) {
2819 return CommandCost(STR_ERROR_SITE_UNSUITABLE);
2820 }
2821
2822 if (IsBridgeAbove(tile_cur)) return CommandCost(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
2823
2824 /* Get the water class of the water tile before it is cleared.*/
2825 WaterClass wc = GetWaterClass(tile_cur);
2826
2827 bool add_cost = !IsWaterTile(tile_cur);
2828 ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile_cur);
2829 if (ret.Failed()) return ret;
2830 if (add_cost) cost.AddCost(ret);
2831
2832 tile_cur += TileOffsByDiagDir(direction);
2833 if (!IsTileType(tile_cur, MP_WATER) || !IsTileFlat(tile_cur)) {
2834 return CommandCost(STR_ERROR_SITE_UNSUITABLE);
2835 }
2836
2837 TileArea dock_area = TileArea(tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
2838 _dock_w_chk[direction], _dock_h_chk[direction]);
2839
2840 /* middle */
2841 Station *st = nullptr;
2842 ret = FindJoiningStation(INVALID_STATION, station_to_join, adjacent, dock_area, &st);
2843 if (ret.Failed()) return ret;
2844
2845 /* Distant join */
2846 if (st == nullptr && distant_join) st = Station::GetIfValid(station_to_join);
2847
2848 ret = BuildStationPart(&st, flags, reuse, dock_area, STATIONNAMING_DOCK);
2849 if (ret.Failed()) return ret;
2850
2851 if (flags & DC_EXEC) {
2852 st->ship_station.Add(tile);
2853 TileIndex flat_tile = tile + TileOffsByDiagDir(direction);
2854 st->ship_station.Add(flat_tile);
2855 st->AddFacility(FACIL_DOCK, tile);
2856
2857 st->rect.BeforeAddRect(dock_area.tile, dock_area.w, dock_area.h, StationRect::ADD_TRY);
2858
2859 /* If the water part of the dock is on a canal, update infrastructure counts.
2860 * This is needed as we've cleared that tile before.
2861 * Clearing object tiles may result in water tiles which are already accounted for in the water infrastructure total.
2862 * See: MakeWaterKeepingClass() */
2863 if (wc == WATER_CLASS_CANAL && !(HasTileWaterClass(flat_tile) && GetWaterClass(flat_tile) == WATER_CLASS_CANAL && IsTileOwner(flat_tile, _current_company))) {
2864 Company::Get(st->owner)->infrastructure.water++;
2865 }
2866 Company::Get(st->owner)->infrastructure.station += 2;
2867
2868 MakeDock(tile, st->owner, st->index, direction, wc);
2869 UpdateStationDockingTiles(st);
2870
2871 st->AfterStationTileSetChange(true, STATION_DOCK);
2872 }
2873
2874 return cost;
2875}
2876
2877void RemoveDockingTile(TileIndex t)
2878{
2879 for (DiagDirection d = DIAGDIR_BEGIN; d != DIAGDIR_END; d++) {
2880 TileIndex tile = t + TileOffsByDiagDir(d);
2881 if (!IsValidTile(tile)) continue;
2882
2883 if (IsTileType(tile, MP_STATION)) {
2884 Station *st = Station::GetByTile(tile);
2885 if (st != nullptr) UpdateStationDockingTiles(st);
2886 } else if (IsTileType(tile, MP_INDUSTRY)) {
2887 Station *neutral = Industry::GetByTile(tile)->neutral_station;
2888 if (neutral != nullptr) UpdateStationDockingTiles(neutral);
2889 }
2890 }
2891}
2892
2898 void ClearDockingTilesCheckingNeighbours(TileIndex tile)
2899{
2900 assert(IsValidTile(tile));
2901
2902 /* Clear and maybe re-set docking tile */
2903 for (DiagDirection d = DIAGDIR_BEGIN; d != DIAGDIR_END; d++) {
2904 TileIndex docking_tile = tile + TileOffsByDiagDir(d);
2905 if (!IsValidTile(docking_tile)) continue;
2906
2907 if (IsPossibleDockingTile(docking_tile)) {
2908 SetDockingTile(docking_tile, false);
2909 CheckForDockingTile(docking_tile);
2910 }
2911 }
2912}
2913
2919 static TileIndex FindDockLandPart(TileIndex t)
2920{
2921 assert(IsDockTile(t));
2922
2923 StationGfx gfx = GetStationGfx(t);
2924 if (gfx < GFX_DOCK_BASE_WATER_PART) return t;
2925
2926 for (DiagDirection d = DIAGDIR_BEGIN; d != DIAGDIR_END; d++) {
2927 TileIndex tile = t + TileOffsByDiagDir(d);
2928 if (!IsValidTile(tile)) continue;
2929 if (!IsDockTile(tile)) continue;
2930 if (GetStationGfx(tile) < GFX_DOCK_BASE_WATER_PART && tile + TileOffsByDiagDir(GetDockDirection(tile)) == t) return tile;
2931 }
2932
2933 return INVALID_TILE;
2934}
2935
2942 static CommandCost RemoveDock(TileIndex tile, DoCommandFlag flags)
2943{
2944 Station *st = Station::GetByTile(tile);
2945 CommandCost ret = CheckOwnership(st->owner);
2946 if (ret.Failed()) return ret;
2947
2948 if (!IsDockTile(tile)) return CMD_ERROR;
2949
2950 TileIndex tile1 = FindDockLandPart(tile);
2951 if (tile1 == INVALID_TILE) return CMD_ERROR;
2952 TileIndex tile2 = tile1 + TileOffsByDiagDir(GetDockDirection(tile1));
2953
2954 ret = EnsureNoVehicleOnGround(tile1);
2955 if (ret.Succeeded()) ret = EnsureNoVehicleOnGround(tile2);
2956 if (ret.Failed()) return ret;
2957
2958 if (flags & DC_EXEC) {
2959 DoClearSquare(tile1);
2960 MarkTileDirtyByTile(tile1);
2961 MakeWaterKeepingClass(tile2, st->owner);
2962
2963 st->rect.AfterRemoveTile(st, tile1);
2964 st->rect.AfterRemoveTile(st, tile2);
2965
2966 MakeShipStationAreaSmaller(st);
2967 if (st->ship_station.tile == INVALID_TILE) {
2968 st->ship_station.Clear();
2969 st->docking_station.Clear();
2970 st->facilities &= ~FACIL_DOCK;
2971 SetWindowClassesDirty(WC_VEHICLE_ORDERS);
2972 }
2973
2974 Company::Get(st->owner)->infrastructure.station -= 2;
2975
2976 st->AfterStationTileSetChange(false, STATION_DOCK);
2977
2978 ClearDockingTilesCheckingNeighbours(tile1);
2979 ClearDockingTilesCheckingNeighbours(tile2);
2980
2981 for (Ship *s : Ship::Iterate()) {
2982 /* Find all ships going to our dock. */
2983 if (s->current_order.GetDestination() != st->index) {
2984 continue;
2985 }
2986
2987 /* Find ships that are marked as "loading" but are no longer on a
2988 * docking tile. Force them to leave the station (as they were loading
2989 * on the removed dock). */
2990 if (s->current_order.IsType(OT_LOADING) && !(IsDockingTile(s->tile) && IsShipDestinationTile(s->tile, st->index))) {
2991 s->LeaveStation();
2992 }
2993
2994 /* If we no longer have a dock, mark the order as invalid and send
2995 * the ship to the next order (or, if there is none, make it
2996 * wander the world). */
2997 if (s->current_order.IsType(OT_GOTO_STATION) && !(st->facilities & FACIL_DOCK)) {
2998 s->SetDestTile(s->GetOrderStationLocation(st->index));
2999 }
3000 }
3001 }
3002
3003 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_STATION_DOCK]);
3004}
3005
3006#include "table/station_land.h"
3007
3014 const DrawTileSprites *GetStationTileLayout(StationType st, uint8_t gfx)
3015{
3016 const auto &layouts = _station_display_datas[st];
3017 if (gfx >= layouts.size()) gfx &= 1;
3018 return layouts.data() + gfx;
3019}
3020
3030 bool SplitGroundSpriteForOverlay(const TileInfo *ti, SpriteID *ground, RailTrackOffset *overlay_offset)
3031{
3032 bool snow_desert;
3033 switch (*ground) {
3034 case SPR_RAIL_TRACK_X:
3035 case SPR_MONO_TRACK_X:
3036 case SPR_MGLV_TRACK_X:
3037 snow_desert = false;
3038 *overlay_offset = RTO_X;
3039 break;
3040
3041 case SPR_RAIL_TRACK_Y:
3042 case SPR_MONO_TRACK_Y:
3043 case SPR_MGLV_TRACK_Y:
3044 snow_desert = false;
3045 *overlay_offset = RTO_Y;
3046 break;
3047
3048 case SPR_RAIL_TRACK_X_SNOW:
3049 case SPR_MONO_TRACK_X_SNOW:
3050 case SPR_MGLV_TRACK_X_SNOW:
3051 snow_desert = true;
3052 *overlay_offset = RTO_X;
3053 break;
3054
3055 case SPR_RAIL_TRACK_Y_SNOW:
3056 case SPR_MONO_TRACK_Y_SNOW:
3057 case SPR_MGLV_TRACK_Y_SNOW:
3058 snow_desert = true;
3059 *overlay_offset = RTO_Y;
3060 break;
3061
3062 default:
3063 return false;
3064 }
3065
3066 if (ti != nullptr) {
3067 /* Decide snow/desert from tile */
3068 switch (_settings_game.game_creation.landscape) {
3069 case LT_ARCTIC:
3070 snow_desert = (uint)ti->z > GetSnowLine() * TILE_HEIGHT;
3071 break;
3072
3073 case LT_TROPIC:
3074 snow_desert = GetTropicZone(ti->tile) == TROPICZONE_DESERT;
3075 break;
3076
3077 default:
3078 break;
3079 }
3080 }
3081
3082 *ground = snow_desert ? SPR_FLAT_SNOW_DESERT_TILE : SPR_FLAT_GRASS_TILE;
3083 return true;
3084}
3085
3086static void DrawTile_Station(TileInfo *ti)
3087{
3088 const NewGRFSpriteLayout *layout = nullptr;
3089 DrawTileSprites tmp_rail_layout;
3090 const DrawTileSprites *t = nullptr;
3091 int32_t total_offset;
3092 const RailTypeInfo *rti = nullptr;
3093 uint32_t relocation = 0;
3094 uint32_t ground_relocation = 0;
3095 BaseStation *st = nullptr;
3096 const StationSpec *statspec = nullptr;
3097 uint tile_layout = 0;
3098
3099 if (HasStationRail(ti->tile)) {
3100 rti = GetRailTypeInfo(GetRailType(ti->tile));
3101 total_offset = rti->GetRailtypeSpriteOffset();
3102
3103 if (IsCustomStationSpecIndex(ti->tile)) {
3104 /* look for customization */
3105 st = BaseStation::GetByTile(ti->tile);
3106 statspec = st->speclist[GetCustomStationSpecIndex(ti->tile)].spec;
3107
3108 if (statspec != nullptr) {
3109 tile_layout = GetStationGfx(ti->tile);
3110
3111 if (HasBit(statspec->callback_mask, CBM_STATION_DRAW_TILE_LAYOUT)) {
3112 uint16_t callback = GetStationCallback(CBID_STATION_DRAW_TILE_LAYOUT, 0, 0, statspec, st, ti->tile);
3113 if (callback != CALLBACK_FAILED) tile_layout = (callback & ~1) + GetRailStationAxis(ti->tile);
3114 }
3115
3116 /* Ensure the chosen tile layout is valid for this custom station */
3117 if (!statspec->renderdata.empty()) {
3118 layout = &statspec->renderdata[tile_layout < statspec->renderdata.size() ? tile_layout : (uint)GetRailStationAxis(ti->tile)];
3119 if (!layout->NeedsPreprocessing()) {
3120 t = layout;
3121 layout = nullptr;
3122 }
3123 }
3124 }
3125 }
3126 } else {
3127 total_offset = 0;
3128 }
3129
3130 StationGfx gfx = GetStationGfx(ti->tile);
3131 if (IsAirport(ti->tile)) {
3132 gfx = GetAirportGfx(ti->tile);
3133 if (gfx >= NEW_AIRPORTTILE_OFFSET) {
3134 const AirportTileSpec *ats = AirportTileSpec::Get(gfx);
3135 if (ats->grf_prop.spritegroup[0] != nullptr && DrawNewAirportTile(ti, Station::GetByTile(ti->tile), ats)) {
3136 return;
3137 }
3138 /* No sprite group (or no valid one) found, meaning no graphics associated.
3139 * Use the substitute one instead */
3140 assert(ats->grf_prop.subst_id != INVALID_AIRPORTTILE);
3141 gfx = ats->grf_prop.subst_id;
3142 }
3143 switch (gfx) {
3144 case APT_RADAR_GRASS_FENCE_SW:
3145 t = &_station_display_datas_airport_radar_grass_fence_sw[GetAnimationFrame(ti->tile)];
3146 break;
3147 case APT_GRASS_FENCE_NE_FLAG:
3148 t = &_station_display_datas_airport_flag_grass_fence_ne[GetAnimationFrame(ti->tile)];
3149 break;
3150 case APT_RADAR_FENCE_SW:
3151 t = &_station_display_datas_airport_radar_fence_sw[GetAnimationFrame(ti->tile)];
3152 break;
3153 case APT_RADAR_FENCE_NE:
3154 t = &_station_display_datas_airport_radar_fence_ne[GetAnimationFrame(ti->tile)];
3155 break;
3156 case APT_GRASS_FENCE_NE_FLAG_2:
3157 t = &_station_display_datas_airport_flag_grass_fence_ne_2[GetAnimationFrame(ti->tile)];
3158 break;
3159 }
3160 }
3161
3162 Owner owner = GetTileOwner(ti->tile);
3163
3164 PaletteID palette;
3165 if (Company::IsValidID(owner)) {
3166 palette = COMPANY_SPRITE_COLOUR(owner);
3167 } else {
3168 /* Some stations are not owner by a company, namely oil rigs */
3169 palette = PALETTE_TO_GREY;
3170 }
3171
3172 if (layout == nullptr && (t == nullptr || t->seq == nullptr)) t = GetStationTileLayout(GetStationType(ti->tile), gfx);
3173
3174 /* don't show foundation for docks */
3175 if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile)) {
3176 if (statspec != nullptr && HasBit(statspec->flags, SSF_CUSTOM_FOUNDATIONS)) {
3177 /* Station has custom foundations.
3178 * Check whether the foundation continues beyond the tile's upper sides. */
3179 uint edge_info = 0;
3180 auto [slope, z] = GetFoundationPixelSlope(ti->tile);
3181 if (!HasFoundationNW(ti->tile, slope, z)) SetBit(edge_info, 0);
3182 if (!HasFoundationNE(ti->tile, slope, z)) SetBit(edge_info, 1);
3183 SpriteID image = GetCustomStationFoundationRelocation(statspec, st, ti->tile, tile_layout, edge_info);
3184 if (image == 0) goto draw_default_foundation;
3185
3186 if (HasBit(statspec->flags, SSF_EXTENDED_FOUNDATIONS)) {
3187 /* Station provides extended foundations. */
3188
3189 static const uint8_t foundation_parts[] = {
3190 0, 0, 0, 0, // Invalid, Invalid, Invalid, SLOPE_SW
3191 0, 1, 2, 3, // Invalid, SLOPE_EW, SLOPE_SE, SLOPE_WSE
3192 0, 4, 5, 6, // Invalid, SLOPE_NW, SLOPE_NS, SLOPE_NWS
3193 7, 8, 9 // SLOPE_NE, SLOPE_ENW, SLOPE_SEN
3194 };
3195
3196 AddSortableSpriteToDraw(image + foundation_parts[ti->tileh], PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
3197 } else {
3198 /* Draw simple foundations, built up from 8 possible foundation sprites. */
3199
3200 /* Each set bit represents one of the eight composite sprites to be drawn.
3201 * 'Invalid' entries will not drawn but are included for completeness. */
3202 static const uint8_t composite_foundation_parts[] = {
3203 /* Invalid (00000000), Invalid (11010001), Invalid (11100100), SLOPE_SW (11100000) */
3204 0x00, 0xD1, 0xE4, 0xE0,
3205 /* Invalid (11001010), SLOPE_EW (11001001), SLOPE_SE (11000100), SLOPE_WSE (11000000) */
3206 0xCA, 0xC9, 0xC4, 0xC0,
3207 /* Invalid (11010010), SLOPE_NW (10010001), SLOPE_NS (11100100), SLOPE_NWS (10100000) */
3208 0xD2, 0x91, 0xE4, 0xA0,
3209 /* SLOPE_NE (01001010), SLOPE_ENW (00001001), SLOPE_SEN (01000100) */
3210 0x4A, 0x09, 0x44
3211 };
3212
3213 uint8_t parts = composite_foundation_parts[ti->tileh];
3214
3215 /* If foundations continue beyond the tile's upper sides then
3216 * mask out the last two pieces. */
3217 if (HasBit(edge_info, 0)) ClrBit(parts, 6);
3218 if (HasBit(edge_info, 1)) ClrBit(parts, 7);
3219
3220 if (parts == 0) {
3221 /* We always have to draw at least one sprite to make sure there is a boundingbox and a sprite with the
3222 * correct offset for the childsprites.
3223 * So, draw the (completely empty) sprite of the default foundations. */
3224 goto draw_default_foundation;
3225 }
3226
3227 StartSpriteCombine();
3228 for (int i = 0; i < 8; i++) {
3229 if (HasBit(parts, i)) {
3230 AddSortableSpriteToDraw(image + i, PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
3231 }
3232 }
3233 EndSpriteCombine();
3234 }
3235
3236 OffsetGroundSprite(0, -8);
3237 ti->z += ApplyPixelFoundationToSlope(FOUNDATION_LEVELED, ti->tileh);
3238 } else {
3239draw_default_foundation:
3240 DrawFoundation(ti, FOUNDATION_LEVELED);
3241 }
3242 }
3243
3244 bool draw_ground = false;
3245
3246 if (IsBuoy(ti->tile)) {
3247 DrawWaterClassGround(ti);
3248 SpriteID sprite = GetCanalSprite(CF_BUOY, ti->tile);
3249 if (sprite != 0) total_offset = sprite - SPR_IMG_BUOY;
3250 } else if (IsDock(ti->tile) || (IsOilRig(ti->tile) && IsTileOnWater(ti->tile))) {
3251 if (ti->tileh == SLOPE_FLAT) {
3252 DrawWaterClassGround(ti);
3253 } else {
3254 assert(IsDock(ti->tile));
3255 TileIndex water_tile = ti->tile + TileOffsByDiagDir(GetDockDirection(ti->tile));
3256 WaterClass wc = HasTileWaterClass(water_tile) ? GetWaterClass(water_tile) : WATER_CLASS_INVALID;
3257 if (wc == WATER_CLASS_SEA) {
3258 DrawShoreTile(ti->tileh);
3259 } else {
3260 DrawClearLandTile(ti, 3);
3261 }
3262 }
3263 } else if (IsRoadWaypointTile(ti->tile)) {
3264 RoadBits bits = AxisToRoadBits(GetDriveThroughStopAxis(ti->tile));
3265 RoadType road_rt = GetRoadTypeRoad(ti->tile);
3266 RoadType tram_rt = GetRoadTypeTram(ti->tile);
3267 RoadBits road = (road_rt != INVALID_ROADTYPE) ? bits : ROAD_NONE;
3268 RoadBits tram = (tram_rt != INVALID_ROADTYPE) ? bits : ROAD_NONE;
3269 const RoadTypeInfo *road_rti = (road_rt != INVALID_ROADTYPE) ? GetRoadTypeInfo(road_rt) : nullptr;
3270 const RoadTypeInfo *tram_rti = (tram_rt != INVALID_ROADTYPE) ? GetRoadTypeInfo(tram_rt) : nullptr;
3271
3272 if (ti->tileh != SLOPE_FLAT) {
3273 DrawFoundation(ti, FOUNDATION_LEVELED);
3274 }
3275
3276 DrawRoadGroundSprites(ti, road, tram, road_rti, tram_rti, GetRoadWaypointRoadside(ti->tile), IsRoadWaypointOnSnowOrDesert(ti->tile));
3277 } else {
3278 if (layout != nullptr) {
3279 /* Sprite layout which needs preprocessing */
3280 bool separate_ground = HasBit(statspec->flags, SSF_SEPARATE_GROUND);
3281 uint32_t var10_values = layout->PrepareLayout(total_offset, rti->fallback_railtype, 0, 0, separate_ground);
3282 for (uint8_t var10 : SetBitIterator(var10_values)) {
3283 uint32_t var10_relocation = GetCustomStationRelocation(statspec, st, ti->tile, var10);
3284 layout->ProcessRegisters(var10, var10_relocation, separate_ground);
3285 }
3286 tmp_rail_layout.seq = layout->GetLayout(&tmp_rail_layout.ground);
3287 t = &tmp_rail_layout;
3288 total_offset = 0;
3289 } else if (statspec != nullptr) {
3290 /* Simple sprite layout */
3291 ground_relocation = relocation = GetCustomStationRelocation(statspec, st, ti->tile, 0);
3292 if (HasBit(statspec->flags, SSF_SEPARATE_GROUND)) {
3293 ground_relocation = GetCustomStationRelocation(statspec, st, ti->tile, 1);
3294 }
3295 ground_relocation += rti->fallback_railtype;
3296 }
3297
3298 draw_ground = true;
3299 }
3300
3301 if (draw_ground && !IsAnyRoadStop(ti->tile)) {
3302 SpriteID image = t->ground.sprite;
3303 PaletteID pal = t->ground.pal;
3304 RailTrackOffset overlay_offset;
3305 if (rti != nullptr && rti->UsesOverlay() && SplitGroundSpriteForOverlay(ti, &image, &overlay_offset)) {
3306 SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
3307 DrawGroundSprite(image, PAL_NONE);
3308 DrawGroundSprite(ground + overlay_offset, PAL_NONE);
3309
3310 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationReservation(ti->tile)) {
3311 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
3312 DrawGroundSprite(overlay + overlay_offset, PALETTE_CRASH);
3313 }
3314 } else {
3315 image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
3316 if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
3317 DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
3318
3319 /* PBS debugging, draw reserved tracks darker */
3320 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationRail(ti->tile) && HasStationReservation(ti->tile)) {
3321 DrawGroundSprite(GetRailStationAxis(ti->tile) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH);
3322 }
3323 }
3324 }
3325
3326 if (HasStationRail(ti->tile) && HasRailCatenaryDrawn(GetRailType(ti->tile))) DrawRailCatenary(ti);
3327
3328 if (IsAnyRoadStop(ti->tile)) {
3329 RoadType road_rt = GetRoadTypeRoad(ti->tile);
3330 RoadType tram_rt = GetRoadTypeTram(ti->tile);
3331 const RoadTypeInfo *road_rti = road_rt == INVALID_ROADTYPE ? nullptr : GetRoadTypeInfo(road_rt);
3332 const RoadTypeInfo *tram_rti = tram_rt == INVALID_ROADTYPE ? nullptr : GetRoadTypeInfo(tram_rt);
3333
3334 StationGfx view = GetStationGfx(ti->tile);
3335 StationType type = GetStationType(ti->tile);
3336
3337 const RoadStopSpec *stopspec = GetRoadStopSpec(ti->tile);
3338 RoadStopDrawMode stop_draw_mode{};
3339 if (stopspec != nullptr) {
3340 stop_draw_mode = stopspec->draw_mode;
3341 st = BaseStation::GetByTile(ti->tile);
3342 RoadStopResolverObject object(stopspec, st, ti->tile, INVALID_ROADTYPE, type, view);
3343 const SpriteGroup *group = object.Resolve();
3344 if (group != nullptr && group->type == SGT_TILELAYOUT) {
3345 if (HasBit(stopspec->flags, RSF_DRAW_MODE_REGISTER)) {
3346 stop_draw_mode = static_cast<RoadStopDrawMode>(GetRegister(0x100));
3347 }
3348 if (type == STATION_ROADWAYPOINT && (stop_draw_mode & ROADSTOP_DRAW_MODE_WAYP_GROUND)) {
3349 draw_ground = true;
3350 }
3351 t = ((const TileLayoutSpriteGroup *)group)->ProcessRegisters(nullptr);
3352 }
3353 }
3354
3355 /* Draw ground sprite */
3356 if (draw_ground) {
3357 SpriteID image = t->ground.sprite;
3358 PaletteID pal = t->ground.pal;
3359 image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
3360 if (GB(image, 0, SPRITE_WIDTH) != 0) {
3361 if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
3362 DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
3363 }
3364 }
3365
3366 if (IsDriveThroughStopTile(ti->tile)) {
3367 if (type != STATION_ROADWAYPOINT && (stopspec == nullptr || (stop_draw_mode & ROADSTOP_DRAW_MODE_OVERLAY) != 0)) {
3368 uint sprite_offset = GetDriveThroughStopAxis(ti->tile) == AXIS_X ? 1 : 0;
3369 DrawRoadOverlays(ti, PAL_NONE, road_rti, tram_rti, sprite_offset, sprite_offset);
3370 }
3371 } else {
3372 /* Non-drivethrough road stops are only valid for roads. */
3373 assert(road_rt != INVALID_ROADTYPE && tram_rt == INVALID_ROADTYPE);
3374
3375 if ((stopspec == nullptr || (stop_draw_mode & ROADSTOP_DRAW_MODE_ROAD) != 0) && road_rti->UsesOverlay()) {
3376 SpriteID ground = GetCustomRoadSprite(road_rti, ti->tile, ROTSG_ROADSTOP);
3377 DrawGroundSprite(ground + view, PAL_NONE);
3378 }
3379 }
3380
3381 if (stopspec == nullptr || !HasBit(stopspec->flags, RSF_NO_CATENARY)) {
3382 /* Draw road, tram catenary */
3383 DrawRoadCatenary(ti);
3384 }
3385 }
3386
3387 if (IsRailWaypoint(ti->tile)) {
3388 /* Don't offset the waypoint graphics; they're always the same. */
3389 total_offset = 0;
3390 }
3391
3392 DrawRailTileSeq(ti, t, TO_BUILDINGS, total_offset, relocation, palette);
3393}
3394
3395void StationPickerDrawSprite(int x, int y, StationType st, RailType railtype, RoadType roadtype, int image)
3396{
3397 int32_t total_offset = 0;
3398 PaletteID pal = COMPANY_SPRITE_COLOUR(_local_company);
3399 const DrawTileSprites *t = GetStationTileLayout(st, image);
3400 const RailTypeInfo *railtype_info = nullptr;
3401
3402 if (railtype != INVALID_RAILTYPE) {
3403 railtype_info = GetRailTypeInfo(railtype);
3404 total_offset = railtype_info->GetRailtypeSpriteOffset();
3405 }
3406
3407 SpriteID img = t->ground.sprite;
3408 RailTrackOffset overlay_offset;
3409 if (railtype_info != nullptr && railtype_info->UsesOverlay() && SplitGroundSpriteForOverlay(nullptr, &img, &overlay_offset)) {
3410 SpriteID ground = GetCustomRailSprite(railtype_info, INVALID_TILE, RTSG_GROUND);
3411 DrawSprite(img, PAL_NONE, x, y);
3412 DrawSprite(ground + overlay_offset, PAL_NONE, x, y);
3413 } else {
3414 DrawSprite(img + total_offset, HasBit(img, PALETTE_MODIFIER_COLOUR) ? pal : PAL_NONE, x, y);
3415 }
3416
3417 if (roadtype != INVALID_ROADTYPE) {
3418 const RoadTypeInfo *roadtype_info = GetRoadTypeInfo(roadtype);
3419 if (image >= 4) {
3420 /* Drive-through stop */
3421 uint sprite_offset = 5 - image;
3422
3423 /* Road underlay takes precedence over tram */
3424 if (roadtype_info->UsesOverlay()) {
3425 SpriteID ground = GetCustomRoadSprite(roadtype_info, INVALID_TILE, ROTSG_GROUND);
3426 DrawSprite(ground + sprite_offset, PAL_NONE, x, y);
3427
3428 SpriteID overlay = GetCustomRoadSprite(roadtype_info, INVALID_TILE, ROTSG_OVERLAY);
3429 if (overlay) DrawSprite(overlay + sprite_offset, PAL_NONE, x, y);
3430 } else if (RoadTypeIsTram(roadtype)) {
3431 DrawSprite(SPR_TRAMWAY_TRAM + sprite_offset, PAL_NONE, x, y);
3432 }
3433 } else {
3434 /* Bay stop */
3435 if (RoadTypeIsRoad(roadtype) && roadtype_info->UsesOverlay()) {
3436 SpriteID ground = GetCustomRoadSprite(roadtype_info, INVALID_TILE, ROTSG_ROADSTOP);
3437 DrawSprite(ground + image, PAL_NONE, x, y);
3438 }
3439 }
3440 }
3441
3442 /* Default waypoint has no railtype specific sprites */
3443 DrawRailTileSeqInGUI(x, y, t, (st == STATION_WAYPOINT || st == STATION_ROADWAYPOINT) ? 0 : total_offset, 0, pal);
3444}
3445
3446static int GetSlopePixelZ_Station(TileIndex tile, uint, uint, bool)
3447{
3448 return GetTileMaxPixelZ(tile);
3449}
3450
3451static Foundation GetFoundation_Station(TileIndex, Slope tileh)
3452{
3453 return FlatteningFoundation(tileh);
3454}
3455
3456static void FillTileDescRoadStop(TileIndex tile, TileDesc *td)
3457{
3458 RoadType road_rt = GetRoadTypeRoad(tile);
3459 RoadType tram_rt = GetRoadTypeTram(tile);
3460 Owner road_owner = INVALID_OWNER;
3461 Owner tram_owner = INVALID_OWNER;
3462 if (road_rt != INVALID_ROADTYPE) {
3463 const RoadTypeInfo *rti = GetRoadTypeInfo(road_rt);
3464 td->roadtype = rti->strings.name;
3465 td->road_speed = rti->max_speed / 2;
3466 road_owner = GetRoadOwner(tile, RTT_ROAD);
3467 }
3468
3469 if (tram_rt != INVALID_ROADTYPE) {
3470 const RoadTypeInfo *rti = GetRoadTypeInfo(tram_rt);
3471 td->tramtype = rti->strings.name;
3472 td->tram_speed = rti->max_speed / 2;
3473 tram_owner = GetRoadOwner(tile, RTT_TRAM);
3474 }
3475
3476 if (IsDriveThroughStopTile(tile)) {
3477 /* Is there a mix of owners? */
3478 if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
3479 (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
3480 uint i = 1;
3481 if (road_owner != INVALID_OWNER) {
3482 td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
3483 td->owner[i] = road_owner;
3484 i++;
3485 }
3486 if (tram_owner != INVALID_OWNER) {
3487 td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
3488 td->owner[i] = tram_owner;
3489 }
3490 }
3491 }
3492}
3493
3494void FillTileDescRailStation(TileIndex tile, TileDesc *td)
3495{
3496 const StationSpec *spec = GetStationSpec(tile);
3497
3498 if (spec != nullptr) {
3499 td->station_class = StationClass::Get(spec->class_index)->name;
3500 td->station_name = spec->name;
3501
3502 if (spec->grf_prop.HasGrfFile()) {
3503 const GRFConfig *gc = GetGRFConfig(spec->grf_prop.grfid);
3504 td->grf = gc->GetName();
3505 }
3506 }
3507
3508 const RailTypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
3509 td->rail_speed = rti->max_speed;
3510 td->railtype = rti->strings.name;
3511}
3512
3513void FillTileDescAirport(TileIndex tile, TileDesc *td)
3514{
3515 const AirportSpec *as = Station::GetByTile(tile)->airport.GetSpec();
3516 td->airport_class = AirportClass::Get(as->class_index)->name;
3517 td->airport_name = as->name;
3518
3519 const AirportTileSpec *ats = AirportTileSpec::GetByTile(tile);
3520 td->airport_tile_name = ats->name;
3521
3522 if (as->grf_prop.HasGrfFile()) {
3523 const GRFConfig *gc = GetGRFConfig(as->grf_prop.grfid);
3524 td->grf = gc->GetName();
3525 } else if (ats->grf_prop.HasGrfFile()) {
3526 const GRFConfig *gc = GetGRFConfig(ats->grf_prop.grfid);
3527 td->grf = gc->GetName();
3528 }
3529}
3530
3531static void GetTileDesc_Station(TileIndex tile, TileDesc *td)
3532{
3533 td->owner[0] = GetTileOwner(tile);
3534 td->build_date = BaseStation::GetByTile(tile)->build_date;
3535
3536 if (IsAnyRoadStop(tile)) FillTileDescRoadStop(tile, td);
3537 if (HasStationRail(tile)) FillTileDescRailStation(tile, td);
3538 if (IsAirport(tile)) FillTileDescAirport(tile, td);
3539
3540 StringID str;
3541 switch (GetStationType(tile)) {
3542 default: NOT_REACHED();
3543 case STATION_RAIL: str = STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION; break;
3544 case STATION_AIRPORT:
3545 str = (IsHangar(tile) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR : STR_LAI_STATION_DESCRIPTION_AIRPORT);
3546 break;
3547 case STATION_TRUCK: str = STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA; break;
3548 case STATION_BUS: str = STR_LAI_STATION_DESCRIPTION_BUS_STATION; break;
3549 case STATION_OILRIG: {
3550 const Industry *i = Station::GetByTile(tile)->industry;
3551 const IndustrySpec *is = GetIndustrySpec(i->type);
3552 td->owner[0] = i->owner;
3553 str = is->name;
3554 if (is->grf_prop.HasGrfFile()) td->grf = GetGRFConfig(is->grf_prop.grfid)->GetName();
3555 break;
3556 }
3557 case STATION_DOCK: str = STR_LAI_STATION_DESCRIPTION_SHIP_DOCK; break;
3558 case STATION_BUOY: str = STR_LAI_STATION_DESCRIPTION_BUOY; break;
3559 case STATION_WAYPOINT: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
3560 case STATION_ROADWAYPOINT: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
3561 }
3562 td->str = str;
3563}
3564
3565
3566static TrackStatus GetTileTrackStatus_Station(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
3567{
3568 TrackBits trackbits = TRACK_BIT_NONE;
3569
3570 switch (mode) {
3571 case TRANSPORT_RAIL:
3572 if (HasStationRail(tile) && !IsStationTileBlocked(tile)) {
3573 trackbits = TrackToTrackBits(GetRailStationTrack(tile));
3574 }
3575 break;
3576
3577 case TRANSPORT_WATER:
3578 /* buoy is coded as a station, it is always on open water */
3579 if (IsBuoy(tile)) {
3580 trackbits = TRACK_BIT_ALL;
3581 /* remove tracks that connect NE map edge */
3582 if (TileX(tile) == 0) trackbits &= ~(TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT);
3583 /* remove tracks that connect NW map edge */
3584 if (TileY(tile) == 0) trackbits &= ~(TRACK_BIT_Y | TRACK_BIT_LEFT | TRACK_BIT_UPPER);
3585 }
3586 break;
3587
3588 case TRANSPORT_ROAD:
3589 if (IsAnyRoadStop(tile)) {
3590 RoadTramType rtt = (RoadTramType)sub_mode;
3591 if (!HasTileRoadType(tile, rtt)) break;
3592
3593 if (IsBayRoadStopTile(tile)) {
3594 DiagDirection dir = GetBayRoadStopDir(tile);
3595 if (side != INVALID_DIAGDIR && dir != side) break;
3596 trackbits = DiagDirToDiagTrackBits(dir);
3597 } else {
3598 Axis axis = GetDriveThroughStopAxis(tile);
3599 if (side != INVALID_DIAGDIR && axis != DiagDirToAxis(side)) break;
3600 trackbits = AxisToTrackBits(axis);
3601 }
3602 }
3603 break;
3604
3605 default:
3606 break;
3607 }
3608
3609 return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits), TRACKDIR_BIT_NONE);
3610}
3611
3612
3613static void TileLoop_Station(TileIndex tile)
3614{
3615 /* FIXME -- GetTileTrackStatus_Station -> animated stationtiles
3616 * hardcoded.....not good */
3617 switch (GetStationType(tile)) {
3618 case STATION_AIRPORT:
3619 AirportTileAnimationTrigger(Station::GetByTile(tile), tile, AAT_TILELOOP);
3620 break;
3621
3622 case STATION_DOCK:
3623 if (!IsTileFlat(tile)) break; // only handle water part
3624 [[fallthrough]];
3625
3626 case STATION_OILRIG: //(station part)
3627 case STATION_BUOY:
3628 TileLoop_Water(tile);
3629 break;
3630
3631 case STATION_ROADWAYPOINT: {
3632 switch (_settings_game.game_creation.landscape) {
3633 case LT_ARCTIC:
3634 if (IsRoadWaypointOnSnowOrDesert(tile) != (GetTileZ(tile) > GetSnowLine())) {
3635 ToggleRoadWaypointOnSnowOrDesert(tile);
3636 MarkTileDirtyByTile(tile);
3637 }
3638 break;
3639
3640 case LT_TROPIC:
3641 if (GetTropicZone(tile) == TROPICZONE_DESERT && !IsRoadWaypointOnSnowOrDesert(tile)) {
3642 ToggleRoadWaypointOnSnowOrDesert(tile);
3643 MarkTileDirtyByTile(tile);
3644 }
3645 break;
3646
3647 default: break;
3648 }
3649
3650 HouseZonesBits new_zone = HZB_TOWN_EDGE;
3651 const Town *t = ClosestTownFromTile(tile, UINT_MAX);
3652 if (t != nullptr) {
3653 new_zone = GetTownRadiusGroup(t, tile);
3654 }
3655
3656 /* Adjust road ground type depending on 'new_zone' */
3657 Roadside new_rs = new_zone > HZB_TOWN_EDGE ? ROADSIDE_PAVED : ROADSIDE_GRASS;
3658 Roadside cur_rs = GetRoadWaypointRoadside(tile);
3659
3660 if (new_rs != cur_rs) {
3661 SetRoadWaypointRoadside(tile, cur_rs == ROADSIDE_BARREN ? new_rs : ROADSIDE_BARREN);
3662 MarkTileDirtyByTile(tile);
3663 }
3664 break;
3665 }
3666
3667 default: break;
3668 }
3669}
3670
3671
3672static void AnimateTile_Station(TileIndex tile)
3673{
3674 if (HasStationRail(tile)) {
3675 AnimateStationTile(tile);
3676 return;
3677 }
3678
3679 if (IsAirport(tile)) {
3680 AnimateAirportTile(tile);
3681 return;
3682 }
3683
3684 if (IsAnyRoadStopTile(tile)) {
3685 AnimateRoadStopTile(tile);
3686 return;
3687 }
3688}
3689
3690
3691static bool ClickTile_Station(TileIndex tile)
3692{
3693 const BaseStation *bst = BaseStation::GetByTile(tile);
3694
3695 if (bst->facilities & FACIL_WAYPOINT) {
3696 ShowWaypointWindow(Waypoint::From(bst));
3697 } else if (IsHangar(tile)) {
3698 const Station *st = Station::From(bst);
3699 ShowDepotWindow(st->airport.GetHangarTile(st->airport.GetHangarNum(tile)), VEH_AIRCRAFT);
3700 } else {
3701 ShowStationViewWindow(bst->index);
3702 }
3703 return true;
3704}
3705
3706static VehicleEnterTileStatus VehicleEnter_Station(Vehicle *v, TileIndex tile, int x, int y)
3707{
3708 if (v->type == VEH_TRAIN) {
3709 StationID station_id = GetStationIndex(tile);
3710 if (!v->current_order.ShouldStopAtStation(v, station_id)) return VETSB_CONTINUE;
3711 if (!IsRailStation(tile) || !v->IsFrontEngine()) return VETSB_CONTINUE;
3712
3713 int station_ahead;
3714 int station_length;
3715 int stop = GetTrainStopLocation(station_id, tile, Train::From(v), &station_ahead, &station_length);
3716
3717 /* Stop whenever that amount of station ahead + the distance from the
3718 * begin of the platform to the stop location is longer than the length
3719 * of the platform. Station ahead 'includes' the current tile where the
3720 * vehicle is on, so we need to subtract that. */
3721 if (stop + station_ahead - (int)TILE_SIZE >= station_length) return VETSB_CONTINUE;
3722
3723 DiagDirection dir = DirToDiagDir(v->direction);
3724
3725 x &= 0xF;
3726 y &= 0xF;
3727
3728 if (DiagDirToAxis(dir) != AXIS_X) Swap(x, y);
3729 if (y == TILE_SIZE / 2) {
3730 if (dir != DIAGDIR_SE && dir != DIAGDIR_SW) x = TILE_SIZE - 1 - x;
3731 stop &= TILE_SIZE - 1;
3732
3733 if (x == stop) {
3734 return VETSB_ENTERED_STATION | (VehicleEnterTileStatus)(station_id << VETS_STATION_ID_OFFSET); // enter station
3735 } else if (x < stop) {
3736 v->vehstatus |= VS_TRAIN_SLOWING;
3737 uint16_t spd = std::max(0, (stop - x) * 20 - 15);
3738 if (spd < v->cur_speed) v->cur_speed = spd;
3739 }
3740 }
3741 } else if (v->type == VEH_ROAD) {
3742 RoadVehicle *rv = RoadVehicle::From(v);
3743 if (rv->state < RVSB_IN_ROAD_STOP && !IsReversingRoadTrackdir((Trackdir)rv->state) && rv->frame == 0) {
3744 if (IsStationRoadStop(tile) && rv->IsFrontEngine()) {
3745 /* Attempt to allocate a parking bay in a road stop */
3746 return RoadStop::GetByTile(tile, GetRoadStopType(tile))->Enter(rv) ? VETSB_CONTINUE : VETSB_CANNOT_ENTER;
3747 }
3748 }
3749 }
3750
3751 return VETSB_CONTINUE;
3752}
3753
3758 void TriggerWatchedCargoCallbacks(Station *st)
3759{
3760 /* Collect cargoes accepted since the last big tick. */
3761 CargoTypes cargoes = 0;
3762 for (CargoID cid = 0; cid < NUM_CARGO; cid++) {
3763 if (HasBit(st->goods[cid].status, GoodsEntry::GES_ACCEPTED_BIGTICK)) SetBit(cargoes, cid);
3764 }
3765
3766 /* Anything to do? */
3767 if (cargoes == 0) return;
3768
3769 /* Loop over all houses in the catchment. */
3770 BitmapTileIterator it(st->catchment_tiles);
3771 for (TileIndex tile = it; tile != INVALID_TILE; tile = ++it) {
3772 if (IsTileType(tile, MP_HOUSE)) {
3773 WatchedCargoCallback(tile, cargoes);
3774 }
3775 }
3776}
3777
3784 static bool StationHandleBigTick(BaseStation *st)
3785{
3786 if (!st->IsInUse()) {
3787 if (++st->delete_ctr >= 8) delete st;
3788 return false;
3789 }
3790
3791 if (Station::IsExpected(st)) {
3792 TriggerWatchedCargoCallbacks(Station::From(st));
3793
3794 for (GoodsEntry &ge : Station::From(st)->goods) {
3795 ClrBit(ge.status, GoodsEntry::GES_ACCEPTED_BIGTICK);
3796 }
3797 }
3798
3799
3800 if ((st->facilities & FACIL_WAYPOINT) == 0) UpdateStationAcceptance(Station::From(st), true);
3801
3802 return true;
3803}
3804
3805static inline void byte_inc_sat(uint8_t *p)
3806{
3807 uint8_t b = *p + 1;
3808 if (b != 0) *p = b;
3809}
3810
3817 static void TruncateCargo(const CargoSpec *cs, GoodsEntry *ge, uint amount = UINT_MAX)
3818{
3819 /* If truncating also punish the source stations' ratings to
3820 * decrease the flow of incoming cargo. */
3821
3822 StationCargoAmountMap waiting_per_source;
3823 ge->cargo.Truncate(amount, &waiting_per_source);
3824 for (StationCargoAmountMap::iterator i(waiting_per_source.begin()); i != waiting_per_source.end(); ++i) {
3825 Station *source_station = Station::GetIfValid(i->first);
3826 if (source_station == nullptr) continue;
3827
3828 GoodsEntry &source_ge = source_station->goods[cs->Index()];
3829 source_ge.max_waiting_cargo = std::max(source_ge.max_waiting_cargo, i->second);
3830 }
3831}
3832
3833static void UpdateStationRating(Station *st)
3834{
3835 bool waiting_changed = false;
3836
3837 byte_inc_sat(&st->time_since_load);
3838 byte_inc_sat(&st->time_since_unload);
3839
3840 for (const CargoSpec *cs : CargoSpec::Iterate()) {
3841 GoodsEntry *ge = &st->goods[cs->Index()];
3842 /* Slowly increase the rating back to its original level in the case we
3843 * didn't deliver cargo yet to this station. This happens when a bribe
3844 * failed while you didn't moved that cargo yet to a station. */
3845 if (!ge->HasRating() && ge->rating < INITIAL_STATION_RATING) {
3846 ge->rating++;
3847 }
3848
3849 /* Only change the rating if we are moving this cargo */
3850 if (ge->HasRating()) {
3851 byte_inc_sat(&ge->time_since_pickup);
3852 if (ge->time_since_pickup == 255 && _settings_game.order.selectgoods) {
3853 ClrBit(ge->status, GoodsEntry::GES_RATING);
3854 ge->last_speed = 0;
3855 TruncateCargo(cs, ge);
3856 waiting_changed = true;
3857 continue;
3858 }
3859
3860 bool skip = false;
3861 int rating = 0;
3862 uint waiting = ge->cargo.AvailableCount();
3863
3864 /* num_dests is at least 1 if there is any cargo as
3865 * INVALID_STATION is also a destination.
3866 */
3867 uint num_dests = (uint)ge->cargo.Packets()->MapSize();
3868
3869 /* Average amount of cargo per next hop, but prefer solitary stations
3870 * with only one or two next hops. They are allowed to have more
3871 * cargo waiting per next hop.
3872 * With manual cargo distribution waiting_avg = waiting / 2 as then
3873 * INVALID_STATION is the only destination.
3874 */
3875 uint waiting_avg = waiting / (num_dests + 1);
3876
3877 if (_cheats.station_rating.value) {
3878 ge->rating = rating = MAX_STATION_RATING;
3879 skip = true;
3880 } else if (HasBit(cs->callback_mask, CBM_CARGO_STATION_RATING_CALC)) {
3881 /* Perform custom station rating. If it succeeds the speed, days in transit and
3882 * waiting cargo ratings must not be executed. */
3883
3884 /* NewGRFs expect last speed to be 0xFF when no vehicle has arrived yet. */
3885 uint last_speed = ge->HasVehicleEverTriedLoading() ? ge->last_speed : 0xFF;
3886
3887 uint32_t var18 = ClampTo<uint8_t>(ge->time_since_pickup)
3888 | (ClampTo<uint16_t>(ge->max_waiting_cargo) << 8)
3889 | (ClampTo<uint8_t>(last_speed) << 24);
3890 /* Convert to the 'old' vehicle types */
3891 uint32_t var10 = (st->last_vehicle_type == VEH_INVALID) ? 0x0 : (st->last_vehicle_type + 0x10);
3892 uint16_t callback = GetCargoCallback(CBID_CARGO_STATION_RATING_CALC, var10, var18, cs);
3893 if (callback != CALLBACK_FAILED) {
3894 skip = true;
3895 rating = GB(callback, 0, 14);
3896
3897 /* Simulate a 15 bit signed value */
3898 if (HasBit(callback, 14)) rating -= 0x4000;
3899 }
3900 }
3901
3902 if (!skip) {
3903 int b = ge->last_speed - 85;
3904 if (b >= 0) rating += b >> 2;
3905
3906 uint8_t waittime = ge->time_since_pickup;
3907 if (st->last_vehicle_type == VEH_SHIP) waittime >>= 2;
3908 if (waittime <= 21) rating += 25;
3909 if (waittime <= 12) rating += 25;
3910 if (waittime <= 6) rating += 45;
3911 if (waittime <= 3) rating += 35;
3912
3913 rating -= 90;
3914 if (ge->max_waiting_cargo <= 1500) rating += 55;
3915 if (ge->max_waiting_cargo <= 1000) rating += 35;
3916 if (ge->max_waiting_cargo <= 600) rating += 10;
3917 if (ge->max_waiting_cargo <= 300) rating += 20;
3918 if (ge->max_waiting_cargo <= 100) rating += 10;
3919 }
3920
3921 if (Company::IsValidID(st->owner) && HasBit(st->town->statues, st->owner)) rating += 26;
3922
3923 uint8_t age = ge->last_age;
3924 if (age < 3) rating += 10;
3925 if (age < 2) rating += 10;
3926 if (age < 1) rating += 13;
3927
3928 {
3929 int or_ = ge->rating; // old rating
3930
3931 /* only modify rating in steps of -2, -1, 0, 1 or 2 */
3932 ge->rating = rating = or_ + Clamp(ClampTo<uint8_t>(rating) - or_, -2, 2);
3933
3934 /* if rating is <= 64 and more than 100 items waiting on average per destination,
3935 * remove some random amount of goods from the station */
3936 if (rating <= 64 && waiting_avg >= 100) {
3937 int dec = Random() & 0x1F;
3938 if (waiting_avg < 200) dec &= 7;
3939 waiting -= (dec + 1) * num_dests;
3940 waiting_changed = true;
3941 }
3942
3943 /* if rating is <= 127 and there are any items waiting, maybe remove some goods. */
3944 if (rating <= 127 && waiting != 0) {
3945 uint32_t r = Random();
3946 if (rating <= (int)GB(r, 0, 7)) {
3947 /* Need to have int, otherwise it will just overflow etc. */
3948 waiting = std::max((int)waiting - (int)((GB(r, 8, 2) - 1) * num_dests), 0);
3949 waiting_changed = true;
3950 }
3951 }
3952
3953 /* At some point we really must cap the cargo. Previously this
3954 * was a strict 4095, but now we'll have a less strict, but
3955 * increasingly aggressive truncation of the amount of cargo. */
3956 static const uint WAITING_CARGO_THRESHOLD = 1 << 12;
3957 static const uint WAITING_CARGO_CUT_FACTOR = 1 << 6;
3958 static const uint MAX_WAITING_CARGO = 1 << 15;
3959
3960 if (waiting > WAITING_CARGO_THRESHOLD) {
3961 uint difference = waiting - WAITING_CARGO_THRESHOLD;
3962 waiting -= (difference / WAITING_CARGO_CUT_FACTOR);
3963
3964 waiting = std::min(waiting, MAX_WAITING_CARGO);
3965 waiting_changed = true;
3966 }
3967
3968 /* We can't truncate cargo that's already reserved for loading.
3969 * Thus StoredCount() here. */
3970 if (waiting_changed && waiting < ge->cargo.AvailableCount()) {
3971 /* Feed back the exact own waiting cargo at this station for the
3972 * next rating calculation. */
3973 ge->max_waiting_cargo = 0;
3974
3975 TruncateCargo(cs, ge, ge->cargo.AvailableCount() - waiting);
3976 } else {
3977 /* If the average number per next hop is low, be more forgiving. */
3978 ge->max_waiting_cargo = waiting_avg;
3979 }
3980 }
3981 }
3982 }
3983
3984 StationID index = st->index;
3985 if (waiting_changed) {
3986 SetWindowDirty(WC_STATION_VIEW, index); // update whole window
3987 } else {
3988 SetWindowWidgetDirty(WC_STATION_VIEW, index, WID_SV_ACCEPT_RATING_LIST); // update only ratings list
3989 }
3990}
3991
4000 void RerouteCargo(Station *st, CargoID c, StationID avoid, StationID avoid2)
4001{
4002 GoodsEntry &ge = st->goods[c];
4003
4004 /* Reroute cargo in station. */
4005 ge.cargo.Reroute(UINT_MAX, &ge.cargo, avoid, avoid2, &ge);
4006
4007 /* Reroute cargo staged to be transferred. */
4008 for (Vehicle *v : st->loading_vehicles) {
4009 for (Vehicle *u = v; u != nullptr; u = u->Next()) {
4010 if (u->cargo_type != c) continue;
4011 u->cargo.Reroute(UINT_MAX, &u->cargo, avoid, avoid2, &ge);
4012 }
4013 }
4014}
4015
4024 void DeleteStaleLinks(Station *from)
4025{
4026 for (CargoID c = 0; c < NUM_CARGO; ++c) {
4027 const bool auto_distributed = (_settings_game.linkgraph.GetDistributionType(c) != DT_MANUAL);
4028 GoodsEntry &ge = from->goods[c];
4029 LinkGraph *lg = LinkGraph::GetIfValid(ge.link_graph);
4030 if (lg == nullptr) continue;
4031 std::vector<NodeID> to_remove{};
4032 for (Edge &edge : (*lg)[ge.node].edges) {
4033 Station *to = Station::Get((*lg)[edge.dest_node].station);
4034 assert(to->goods[c].node == edge.dest_node);
4035 assert(TimerGameEconomy::date >= edge.LastUpdate());
4036 auto timeout = TimerGameEconomy::Date(LinkGraph::MIN_TIMEOUT_DISTANCE + (DistanceManhattan(from->xy, to->xy) >> 3));
4037 if (TimerGameEconomy::date - edge.LastUpdate() > timeout) {
4038 bool updated = false;
4039
4040 if (auto_distributed) {
4041 /* Have all vehicles refresh their next hops before deciding to
4042 * remove the node. */
4043 std::vector<Vehicle *> vehicles;
4044 for (OrderList *l : OrderList::Iterate()) {
4045 bool found_from = false;
4046 bool found_to = false;
4047 for (Order *order = l->GetFirstOrder(); order != nullptr; order = order->next) {
4048 if (!order->IsType(OT_GOTO_STATION) && !order->IsType(OT_IMPLICIT)) continue;
4049 if (order->GetDestination() == from->index) {
4050 found_from = true;
4051 if (found_to) break;
4052 } else if (order->GetDestination() == to->index) {
4053 found_to = true;
4054 if (found_from) break;
4055 }
4056 }
4057 if (!found_to || !found_from) continue;
4058 vehicles.push_back(l->GetFirstSharedVehicle());
4059 }
4060
4061 auto iter = vehicles.begin();
4062 while (iter != vehicles.end()) {
4063 Vehicle *v = *iter;
4064 /* Do not refresh links of vehicles that have been stopped in depot for a long time. */
4065 if (!v->IsStoppedInDepot() || TimerGameEconomy::date - v->date_of_last_service <= LinkGraph::STALE_LINK_DEPOT_TIMEOUT) {
4066 LinkRefresher::Run(v, false); // Don't allow merging. Otherwise lg might get deleted.
4067 }
4068 if (edge.LastUpdate() == TimerGameEconomy::date) {
4069 updated = true;
4070 break;
4071 }
4072
4073 Vehicle *next_shared = v->NextShared();
4074 if (next_shared) {
4075 *iter = next_shared;
4076 ++iter;
4077 } else {
4078 iter = vehicles.erase(iter);
4079 }
4080
4081 if (iter == vehicles.end()) iter = vehicles.begin();
4082 }
4083 }
4084
4085 if (!updated) {
4086 /* If it's still considered dead remove it. */
4087 to_remove.emplace_back(to->goods[c].node);
4088 ge.flows.DeleteFlows(to->index);
4089 RerouteCargo(from, c, to->index, from->index);
4090 }
4091 } else if (edge.last_unrestricted_update != EconomyTime::INVALID_DATE && TimerGameEconomy::date - edge.last_unrestricted_update > timeout) {
4092 edge.Restrict();
4093 ge.flows.RestrictFlows(to->index);
4094 RerouteCargo(from, c, to->index, from->index);
4095 } else if (edge.last_restricted_update != EconomyTime::INVALID_DATE && TimerGameEconomy::date - edge.last_restricted_update > timeout) {
4096 edge.Release();
4097 }
4098 }
4099 /* Remove dead edges. */
4100 for (NodeID r : to_remove) (*lg)[ge.node].RemoveEdge(r);
4101
4102 assert(TimerGameEconomy::date >= lg->LastCompression());
4103 if (TimerGameEconomy::date - lg->LastCompression() > LinkGraph::COMPRESSION_INTERVAL) {
4104 lg->Compress();
4105 }
4106 }
4107}
4108
4118 void IncreaseStats(Station *st, CargoID cargo, StationID next_station_id, uint capacity, uint usage, uint32_t time, EdgeUpdateMode mode)
4119{
4120 GoodsEntry &ge1 = st->goods[cargo];
4121 Station *st2 = Station::Get(next_station_id);
4122 GoodsEntry &ge2 = st2->goods[cargo];
4123 LinkGraph *lg = nullptr;
4124 if (ge1.link_graph == INVALID_LINK_GRAPH) {
4125 if (ge2.link_graph == INVALID_LINK_GRAPH) {
4126 if (LinkGraph::CanAllocateItem()) {
4127 lg = new LinkGraph(cargo);
4128 LinkGraphSchedule::instance.Queue(lg);
4129 ge2.link_graph = lg->index;
4130 ge2.node = lg->AddNode(st2);
4131 } else {
4132 Debug(misc, 0, "Can't allocate link graph");
4133 }
4134 } else {
4135 lg = LinkGraph::Get(ge2.link_graph);
4136 }
4137 if (lg) {
4138 ge1.link_graph = lg->index;
4139 ge1.node = lg->AddNode(st);
4140 }
4141 } else if (ge2.link_graph == INVALID_LINK_GRAPH) {
4142 lg = LinkGraph::Get(ge1.link_graph);
4143 ge2.link_graph = lg->index;
4144 ge2.node = lg->AddNode(st2);
4145 } else {
4146 lg = LinkGraph::Get(ge1.link_graph);
4147 if (ge1.link_graph != ge2.link_graph) {
4148 LinkGraph *lg2 = LinkGraph::Get(ge2.link_graph);
4149 if (lg->Size() < lg2->Size()) {
4150 LinkGraphSchedule::instance.Unqueue(lg);
4151 lg2->Merge(lg); // Updates GoodsEntries of lg
4152 lg = lg2;
4153 } else {
4154 LinkGraphSchedule::instance.Unqueue(lg2);
4155 lg->Merge(lg2); // Updates GoodsEntries of lg2
4156 }
4157 }
4158 }
4159 if (lg != nullptr) {
4160 (*lg)[ge1.node].UpdateEdge(ge2.node, capacity, usage, time, mode);
4161 }
4162}
4163
4170 void IncreaseStats(Station *st, const Vehicle *front, StationID next_station_id, uint32_t time)
4171{
4172 for (const Vehicle *v = front; v != nullptr; v = v->Next()) {
4173 if (v->refit_cap > 0) {
4174 /* The cargo count can indeed be higher than the refit_cap if
4175 * wagons have been auto-replaced and subsequently auto-
4176 * refitted to a higher capacity. The cargo gets redistributed
4177 * among the wagons in that case.
4178 * As usage is not such an important figure anyway we just
4179 * ignore the additional cargo then.*/
4180 IncreaseStats(st, v->cargo_type, next_station_id, v->refit_cap,
4181 std::min<uint>(v->refit_cap, v->cargo.StoredCount()), time, EUM_INCREASE);
4182 }
4183 }
4184}
4185
4186/* called for every station each tick */
4187static void StationHandleSmallTick(BaseStation *st)
4188{
4189 if ((st->facilities & FACIL_WAYPOINT) != 0 || !st->IsInUse()) return;
4190
4191 uint8_t b = st->delete_ctr + 1;
4192 if (b >= Ticks::STATION_RATING_TICKS) b = 0;
4193 st->delete_ctr = b;
4194
4195 if (b == 0) UpdateStationRating(Station::From(st));
4196}
4197
4198void OnTick_Station()
4199{
4200 if (_game_mode == GM_EDITOR) return;
4201
4202 for (BaseStation *st : BaseStation::Iterate()) {
4203 StationHandleSmallTick(st);
4204
4205 /* Clean up the link graph about once a week. */
4206 if (Station::IsExpected(st) && (TimerGameTick::counter + st->index) % Ticks::STATION_LINKGRAPH_TICKS == 0) {
4207 DeleteStaleLinks(Station::From(st));
4208 };
4209
4210 /* Spread out big-tick over STATION_ACCEPTANCE_TICKS ticks. */
4211 if ((TimerGameTick::counter + st->index) % Ticks::STATION_ACCEPTANCE_TICKS == 0) {
4212 /* Stop processing this station if it was deleted */
4213 if (!StationHandleBigTick(st)) continue;
4214 }
4215
4216 /* Spread out station animation over STATION_ACCEPTANCE_TICKS ticks. */
4217 if ((TimerGameTick::counter + st->index) % Ticks::STATION_ACCEPTANCE_TICKS == 0) {
4218 TriggerStationAnimation(st, st->xy, SAT_250_TICKS);
4219 TriggerRoadStopAnimation(st, st->xy, SAT_250_TICKS);
4220 if (Station::IsExpected(st)) AirportAnimationTrigger(Station::From(st), AAT_STATION_250_TICKS);
4221 }
4222 }
4223}
4224
4226 static IntervalTimer<TimerGameEconomy> _economy_stations_monthly({TimerGameEconomy::MONTH, TimerGameEconomy::Priority::STATION}, [](auto)
4227{
4228 for (Station *st : Station::Iterate()) {
4229 for (GoodsEntry &ge : st->goods) {
4230 SB(ge.status, GoodsEntry::GES_LAST_MONTH, 1, GB(ge.status, GoodsEntry::GES_CURRENT_MONTH, 1));
4231 ClrBit(ge.status, GoodsEntry::GES_CURRENT_MONTH);
4232 }
4233 }
4234});
4235
4236void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
4237{
4238 ForAllStationsRadius(tile, radius, [&](Station *st) {
4239 if (st->owner == owner && DistanceManhattan(tile, st->xy) <= radius) {
4240 for (GoodsEntry &ge : st->goods) {
4241 if (ge.status != 0) {
4242 ge.rating = ClampTo<uint8_t>(ge.rating + amount);
4243 }
4244 }
4245 }
4246 });
4247}
4248
4249static uint UpdateStationWaiting(Station *st, CargoID type, uint amount, SourceType source_type, SourceID source_id)
4250{
4251 /* We can't allocate a CargoPacket? Then don't do anything
4252 * at all; i.e. just discard the incoming cargo. */
4253 if (!CargoPacket::CanAllocateItem()) return 0;
4254
4255 GoodsEntry &ge = st->goods[type];
4256 amount += ge.amount_fract;
4257 ge.amount_fract = GB(amount, 0, 8);
4258
4259 amount >>= 8;
4260 /* No new "real" cargo item yet. */
4261 if (amount == 0) return 0;
4262
4263 StationID next = ge.GetVia(st->index);
4264 ge.cargo.Append(new CargoPacket(st->index, amount, source_type, source_id), next);
4265 LinkGraph *lg = nullptr;
4266 if (ge.link_graph == INVALID_LINK_GRAPH) {
4267 if (LinkGraph::CanAllocateItem()) {
4268 lg = new LinkGraph(type);
4269 LinkGraphSchedule::instance.Queue(lg);
4270 ge.link_graph = lg->index;
4271 ge.node = lg->AddNode(st);
4272 } else {
4273 Debug(misc, 0, "Can't allocate link graph");
4274 }
4275 } else {
4276 lg = LinkGraph::Get(ge.link_graph);
4277 }
4278 if (lg != nullptr) (*lg)[ge.node].UpdateSupply(amount);
4279
4280 if (!ge.HasRating()) {
4281 InvalidateWindowData(WC_STATION_LIST, st->owner);
4282 SetBit(ge.status, GoodsEntry::GES_RATING);
4283 }
4284
4285 TriggerStationRandomisation(st, st->xy, SRT_NEW_CARGO, type);
4286 TriggerStationAnimation(st, st->xy, SAT_NEW_CARGO, type);
4287 AirportAnimationTrigger(st, AAT_STATION_NEW_CARGO, type);
4288 TriggerRoadStopRandomisation(st, st->xy, RSRT_NEW_CARGO, type);
4289 TriggerRoadStopAnimation(st, st->xy, SAT_NEW_CARGO, type);
4290
4291
4292 SetWindowDirty(WC_STATION_VIEW, st->index);
4293 st->MarkTilesDirty(true);
4294 return amount;
4295}
4296
4297static bool IsUniqueStationName(const std::string &name)
4298{
4299 for (const Station *st : Station::Iterate()) {
4300 if (!st->name.empty() && st->name == name) return false;
4301 }
4302
4303 return true;
4304}
4305
4313 CommandCost CmdRenameStation(DoCommandFlag flags, StationID station_id, const std::string &text)
4314{
4315 Station *st = Station::GetIfValid(station_id);
4316 if (st == nullptr) return CMD_ERROR;
4317
4318 CommandCost ret = CheckOwnership(st->owner);
4319 if (ret.Failed()) return ret;
4320
4321 bool reset = text.empty();
4322
4323 if (!reset) {
4324 if (Utf8StringLength(text) >= MAX_LENGTH_STATION_NAME_CHARS) return CMD_ERROR;
4325 if (!IsUniqueStationName(text)) return CommandCost(STR_ERROR_NAME_MUST_BE_UNIQUE);
4326 }
4327
4328 if (flags & DC_EXEC) {
4329 st->cached_name.clear();
4330 if (reset) {
4331 st->name.clear();
4332 } else {
4333 st->name = text;
4334 }
4335
4336 st->UpdateVirtCoord();
4337 InvalidateWindowData(WC_STATION_LIST, st->owner, 1);
4338 }
4339
4340 return CommandCost();
4341}
4342
4343static void AddNearbyStationsByCatchment(TileIndex tile, StationList &stations, StationList &nearby)
4344{
4345 for (Station *st : nearby) {
4346 if (st->TileIsInCatchment(tile)) stations.insert(st);
4347 }
4348}
4349
4354 const StationList &StationFinder::GetStations()
4355{
4356 if (this->tile != INVALID_TILE) {
4357 if (IsTileType(this->tile, MP_HOUSE)) {
4358 /* Town nearby stations need to be filtered per tile. */
4359 assert(this->w == 1 && this->h == 1);
4360 AddNearbyStationsByCatchment(this->tile, this->stations, Town::GetByTile(this->tile)->stations_near);
4361 } else {
4362 ForAllStationsAroundTiles(*this, [this](Station *st, TileIndex) {
4363 this->stations.insert(st);
4364 return true;
4365 });
4366 }
4367 this->tile = INVALID_TILE;
4368 }
4369 return this->stations;
4370}
4371
4372
4373static bool CanMoveGoodsToStation(const Station *st, CargoID type)
4374{
4375 /* Is the station reserved exclusively for somebody else? */
4376 if (st->owner != OWNER_NONE && st->town->exclusive_counter > 0 && st->town->exclusivity != st->owner) return false;
4377
4378 /* Lowest possible rating, better not to give cargo anymore. */
4379 if (st->goods[type].rating == 0) return false;
4380
4381 /* Selectively servicing stations, and not this one. */
4382 if (_settings_game.order.selectgoods && !st->goods[type].HasVehicleEverTriedLoading()) return false;
4383
4384 if (IsCargoInClass(type, CC_PASSENGERS)) {
4385 /* Passengers are never served by just a truck stop. */
4386 if (st->facilities == FACIL_TRUCK_STOP) return false;
4387 } else {
4388 /* Non-passengers are never served by just a bus stop. */
4389 if (st->facilities == FACIL_BUS_STOP) return false;
4390 }
4391 return true;
4392}
4393
4394uint MoveGoodsToStation(CargoID type, uint amount, SourceType source_type, SourceID source_id, const StationList &all_stations, Owner exclusivity)
4395{
4396 /* Return if nothing to do. Also the rounding below fails for 0. */
4397 if (all_stations.empty()) return 0;
4398 if (amount == 0) return 0;
4399
4400 Station *first_station = nullptr;
4401 typedef std::pair<Station *, uint> StationInfo;
4402 std::vector<StationInfo> used_stations;
4403
4404 for (Station *st : all_stations) {
4405 if (exclusivity != INVALID_OWNER && exclusivity != st->owner) continue;
4406 if (!CanMoveGoodsToStation(st, type)) continue;
4407
4408 /* Avoid allocating a vector if there is only one station to significantly
4409 * improve performance in this common case. */
4410 if (first_station == nullptr) {
4411 first_station = st;
4412 continue;
4413 }
4414 if (used_stations.empty()) {
4415 used_stations.reserve(2);
4416 used_stations.emplace_back(first_station, 0);
4417 }
4418 used_stations.emplace_back(st, 0);
4419 }
4420
4421 /* no stations around at all? */
4422 if (first_station == nullptr) return 0;
4423
4424 if (used_stations.empty()) {
4425 /* only one station around */
4426 amount *= first_station->goods[type].rating + 1;
4427 return UpdateStationWaiting(first_station, type, amount, source_type, source_id);
4428 }
4429
4430 uint company_best[OWNER_NONE + 1] = {}; // best rating for each company, including OWNER_NONE
4431 uint company_sum[OWNER_NONE + 1] = {}; // sum of ratings for each company
4432 uint best_rating = 0;
4433 uint best_sum = 0; // sum of best ratings for each company
4434
4435 for (auto &p : used_stations) {
4436 auto owner = p.first->owner;
4437 auto rating = p.first->goods[type].rating;
4438 if (rating > company_best[owner]) {
4439 best_sum += rating - company_best[owner]; // it's usually faster than iterating companies later
4440 company_best[owner] = rating;
4441 if (rating > best_rating) best_rating = rating;
4442 }
4443 company_sum[owner] += rating;
4444 }
4445
4446 /* From now we'll calculate with fractional cargo amounts.
4447 * First determine how much cargo we really have. */
4448 amount *= best_rating + 1;
4449
4450 uint moving = 0;
4451 for (auto &p : used_stations) {
4452 uint owner = p.first->owner;
4453 /* Multiply the amount by (company best / sum of best for each company) to get cargo allocated to a company
4454 * and by (station rating / sum of ratings in a company) to get the result for a single station. */
4455 p.second = amount * company_best[owner] * p.first->goods[type].rating / best_sum / company_sum[owner];
4456 moving += p.second;
4457 }
4458
4459 /* If there is some cargo left due to rounding issues distribute it among the best rated stations. */
4460 if (amount > moving) {
4461 std::stable_sort(used_stations.begin(), used_stations.end(), [type](const StationInfo &a, const StationInfo &b) {
4462 return b.first->goods[type].rating < a.first->goods[type].rating;
4463 });
4464
4465 assert(amount - moving <= used_stations.size());
4466 for (uint i = 0; i < amount - moving; i++) {
4467 used_stations[i].second++;
4468 }
4469 }
4470
4471 uint moved = 0;
4472 for (auto &p : used_stations) {
4473 moved += UpdateStationWaiting(p.first, type, p.second, source_type, source_id);
4474 }
4475
4476 return moved;
4477}
4478
4479void UpdateStationDockingTiles(Station *st)
4480{
4481 st->docking_station.Clear();
4482
4483 /* For neutral stations, start with the industry area instead of dock area */
4484 const TileArea *area = st->industry != nullptr ? &st->industry->location : &st->ship_station;
4485
4486 if (area->tile == INVALID_TILE) return;
4487
4488 int x = TileX(area->tile);
4489 int y = TileY(area->tile);
4490
4491 /* Expand the area by a tile on each side while
4492 * making sure that we remain inside the map. */
4493 int x2 = std::min<int>(x + area->w + 1, Map::SizeX());
4494 int x1 = std::max<int>(x - 1, 0);
4495
4496 int y2 = std::min<int>(y + area->h + 1, Map::SizeY());
4497 int y1 = std::max<int>(y - 1, 0);
4498
4499 TileArea ta(TileXY(x1, y1), TileXY(x2 - 1, y2 - 1));
4500 for (TileIndex tile : ta) {
4501 if (IsValidTile(tile) && IsPossibleDockingTile(tile)) CheckForDockingTile(tile);
4502 }
4503}
4504
4505void BuildOilRig(TileIndex tile)
4506{
4507 if (!Station::CanAllocateItem()) {
4508 Debug(misc, 0, "Can't allocate station for oilrig at 0x{:X}, reverting to oilrig only", tile);
4509 return;
4510 }
4511
4512 Station *st = new Station(tile);
4513 _station_kdtree.Insert(st->index);
4514 st->town = ClosestTownFromTile(tile, UINT_MAX);
4515
4516 st->string_id = GenerateStationName(st, tile, STATIONNAMING_OILRIG);
4517
4518 assert(IsTileType(tile, MP_INDUSTRY));
4519 /* Mark industry as associated both ways */
4520 st->industry = Industry::GetByTile(tile);
4521 st->industry->neutral_station = st;
4522 DeleteAnimatedTile(tile);
4523 MakeOilrig(tile, st->index, GetWaterClass(tile));
4524
4525 st->owner = OWNER_NONE;
4526 st->airport.type = AT_OILRIG;
4527 st->airport.Add(tile);
4528 st->ship_station.Add(tile);
4529 st->facilities = FACIL_AIRPORT | FACIL_DOCK;
4530 st->build_date = TimerGameCalendar::date;
4531 UpdateStationDockingTiles(st);
4532
4533 st->rect.BeforeAddTile(tile, StationRect::ADD_FORCE);
4534
4535 st->UpdateVirtCoord();
4536
4537 /* An industry tile has now been replaced with a station tile, this may change the overlap between station catchments and industry tiles.
4538 * Recalculate the station catchment for all stations currently in the industry's nearby list.
4539 * Clear the industry's station nearby list first because Station::RecomputeCatchment cannot remove nearby industries in this case. */
4540 if (_settings_game.station.serve_neutral_industries) {
4541 StationList nearby = std::move(st->industry->stations_near);
4542 st->industry->stations_near.clear();
4543 for (Station *near : nearby) {
4544 near->RecomputeCatchment(true);
4545 UpdateStationAcceptance(near, true);
4546 }
4547 }
4548
4549 st->RecomputeCatchment();
4550 UpdateStationAcceptance(st, false);
4551}
4552
4553void DeleteOilRig(TileIndex tile)
4554{
4555 Station *st = Station::GetByTile(tile);
4556
4557 MakeWaterKeepingClass(tile, OWNER_NONE);
4558
4559 /* The oil rig station is not supposed to be shared with anything else */
4560 assert(st->facilities == (FACIL_AIRPORT | FACIL_DOCK) && st->airport.type == AT_OILRIG);
4561 if (st->industry != nullptr && st->industry->neutral_station == st) {
4562 /* Don't leave dangling neutral station pointer */
4563 st->industry->neutral_station = nullptr;
4564 }
4565 delete st;
4566}
4567
4568static void ChangeTileOwner_Station(TileIndex tile, Owner old_owner, Owner new_owner)
4569{
4570 if (IsAnyRoadStopTile(tile)) {
4571 for (RoadTramType rtt : _roadtramtypes) {
4572 /* Update all roadtypes, no matter if they are present */
4573 if (GetRoadOwner(tile, rtt) == old_owner) {
4574 RoadType rt = GetRoadType(tile, rtt);
4575 if (rt != INVALID_ROADTYPE) {
4576 /* A drive-through road-stop has always two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
4577 Company::Get(old_owner)->infrastructure.road[rt] -= 2;
4578 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.road[rt] += 2;
4579 }
4580 SetRoadOwner(tile, rtt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
4581 }
4582 }
4583 }
4584
4585 if (!IsTileOwner(tile, old_owner)) return;
4586
4587 if (new_owner != INVALID_OWNER) {
4588 /* Update company infrastructure counts. Only do it here
4589 * if the new owner is valid as otherwise the clear
4590 * command will do it for us. No need to dirty windows
4591 * here, we'll redraw the whole screen anyway.*/
4592 Company *old_company = Company::Get(old_owner);
4593 Company *new_company = Company::Get(new_owner);
4594
4595 /* Update counts for underlying infrastructure. */
4596 switch (GetStationType(tile)) {
4597 case STATION_RAIL:
4598 case STATION_WAYPOINT:
4599 if (!IsStationTileBlocked(tile)) {
4600 old_company->infrastructure.rail[GetRailType(tile)]--;
4601 new_company->infrastructure.rail[GetRailType(tile)]++;
4602 }
4603 break;
4604
4605 case STATION_BUS:
4606 case STATION_TRUCK:
4607 case STATION_ROADWAYPOINT:
4608 /* Road stops were already handled above. */
4609 break;
4610
4611 case STATION_BUOY:
4612 case STATION_DOCK:
4613 if (GetWaterClass(tile) == WATER_CLASS_CANAL) {
4614 old_company->infrastructure.water--;
4615 new_company->infrastructure.water++;
4616 }
4617 break;
4618
4619 default:
4620 break;
4621 }
4622
4623 /* Update station tile count. */
4624 if (!IsBuoy(tile) && !IsAirport(tile)) {
4625 old_company->infrastructure.station--;
4626 new_company->infrastructure.station++;
4627 }
4628
4629 /* for buoys, owner of tile is owner of water, st->owner == OWNER_NONE */
4630 SetTileOwner(tile, new_owner);
4631 InvalidateWindowClassesData(WC_STATION_LIST, 0);
4632 } else {
4633 if (IsDriveThroughStopTile(tile)) {
4634 /* Remove the drive-through road stop */
4635 if (IsRoadWaypoint(tile)) {
4636 Command<CMD_REMOVE_FROM_ROAD_WAYPOINT>::Do(DC_EXEC | DC_BANKRUPT, tile, tile);
4637 } else {
4638 Command<CMD_REMOVE_ROAD_STOP>::Do(DC_EXEC | DC_BANKRUPT, tile, 1, 1, (GetStationType(tile) == STATION_TRUCK) ? ROADSTOP_TRUCK : ROADSTOP_BUS, false);
4639 }
4640 assert(IsTileType(tile, MP_ROAD));
4641 /* Change owner of tile and all roadtypes */
4642 ChangeTileOwner(tile, old_owner, new_owner);
4643 } else {
4644 Command<CMD_LANDSCAPE_CLEAR>::Do(DC_EXEC | DC_BANKRUPT, tile);
4645 /* Set tile owner of water under (now removed) buoy and dock to OWNER_NONE.
4646 * Update owner of buoy if it was not removed (was in orders).
4647 * Do not update when owned by OWNER_WATER (sea and rivers). */
4648 if ((IsTileType(tile, MP_WATER) || IsBuoyTile(tile)) && IsTileOwner(tile, old_owner)) SetTileOwner(tile, OWNER_NONE);
4649 }
4650 }
4651}
4652
4661 static CommandCost CanRemoveRoadWithStop(TileIndex tile, DoCommandFlag flags)
4662{
4663 /* Water flooding can always clear road stops. */
4664 if (_current_company == OWNER_WATER) return CommandCost();
4665
4666 CommandCost ret;
4667
4668 if (GetRoadTypeTram(tile) != INVALID_ROADTYPE) {
4669 Owner tram_owner = GetRoadOwner(tile, RTT_TRAM);
4670 if (tram_owner != OWNER_NONE) {
4671 ret = CheckOwnership(tram_owner);
4672 if (ret.Failed()) return ret;
4673 }
4674 }
4675
4676 if (GetRoadTypeRoad(tile) != INVALID_ROADTYPE) {
4677 Owner road_owner = GetRoadOwner(tile, RTT_ROAD);
4678 if (road_owner == OWNER_TOWN) {
4679 ret = CheckAllowRemoveRoad(tile, GetAnyRoadBits(tile, RTT_ROAD), OWNER_TOWN, RTT_ROAD, flags);
4680 if (ret.Failed()) return ret;
4681 } else if (road_owner != OWNER_NONE) {
4682 ret = CheckOwnership(road_owner);
4683 if (ret.Failed()) return ret;
4684 }
4685 }
4686
4687 return CommandCost();
4688}
4689
4696 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags)
4697{
4698 if (flags & DC_AUTO) {
4699 switch (GetStationType(tile)) {
4700 default: break;
4701 case STATION_RAIL: return CommandCost(STR_ERROR_MUST_DEMOLISH_RAILROAD);
4702 case STATION_WAYPOINT: return CommandCost(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
4703 case STATION_AIRPORT: return CommandCost(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST);
4704 case STATION_TRUCK: return CommandCost(HasTileRoadType(tile, RTT_TRAM) ? STR_ERROR_MUST_DEMOLISH_CARGO_TRAM_STATION_FIRST : STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
4705 case STATION_BUS: return CommandCost(HasTileRoadType(tile, RTT_TRAM) ? STR_ERROR_MUST_DEMOLISH_PASSENGER_TRAM_STATION_FIRST : STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
4706 case STATION_ROADWAYPOINT: return CommandCost(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
4707 case STATION_BUOY: return CommandCost(STR_ERROR_BUOY_IN_THE_WAY);
4708 case STATION_DOCK: return CommandCost(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST);
4709 case STATION_OILRIG:
4710 SetDParam(1, STR_INDUSTRY_NAME_OIL_RIG);
4711 return CommandCost(STR_ERROR_GENERIC_OBJECT_IN_THE_WAY);
4712 }
4713 }
4714
4715 switch (GetStationType(tile)) {
4716 case STATION_RAIL: return RemoveRailStation(tile, flags);
4717 case STATION_WAYPOINT: return RemoveRailWaypoint(tile, flags);
4718 case STATION_AIRPORT: return RemoveAirport(tile, flags);
4719 case STATION_TRUCK: [[fallthrough]];
4720 case STATION_BUS:
4721 if (IsDriveThroughStopTile(tile)) {
4722 CommandCost remove_road = CanRemoveRoadWithStop(tile, flags);
4723 if (remove_road.Failed()) return remove_road;
4724 }
4725 return RemoveRoadStop(tile, flags);
4726 case STATION_ROADWAYPOINT: {
4727 CommandCost remove_road = CanRemoveRoadWithStop(tile, flags);
4728 if (remove_road.Failed()) return remove_road;
4729 return RemoveRoadWaypointStop(tile, flags);
4730 }
4731 case STATION_BUOY: return RemoveBuoy(tile, flags);
4732 case STATION_DOCK: return RemoveDock(tile, flags);
4733 default: break;
4734 }
4735
4736 return CMD_ERROR;
4737}
4738
4739static CommandCost TerraformTile_Station(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
4740{
4741 if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
4742 /* TODO: If you implement newgrf callback 149 'land slope check', you have to decide what to do with it here.
4743 * TTDP does not call it.
4744 */
4745 if (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new)) {
4746 switch (GetStationType(tile)) {
4747 case STATION_WAYPOINT:
4748 case STATION_RAIL: {
4749 if (!AutoslopeCheckForAxis(tile, z_new, tileh_new, GetRailStationAxis(tile))) break;
4750 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4751 }
4752
4753 case STATION_AIRPORT:
4754 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4755
4756 case STATION_TRUCK:
4757 case STATION_BUS:
4758 case STATION_ROADWAYPOINT: {
4759 if (IsDriveThroughStopTile(tile)) {
4760 if (!AutoslopeCheckForAxis(tile, z_new, tileh_new, GetDriveThroughStopAxis(tile))) break;
4761 } else {
4762 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, GetBayRoadStopDir(tile))) break;
4763 }
4764 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4765 }
4766
4767 default: break;
4768 }
4769 }
4770 }
4771 return Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile);
4772}
4773
4779uint FlowStat::GetShare(StationID st) const
4780{
4781 uint32_t prev = 0;
4782 for (const auto &it : this->shares) {
4783 if (it.second == st) {
4784 return it.first - prev;
4785 } else {
4786 prev = it.first;
4787 }
4788 }
4789 return 0;
4790}
4791
4798StationID FlowStat::GetVia(StationID excluded, StationID excluded2) const
4799{
4800 if (this->unrestricted == 0) return INVALID_STATION;
4801 assert(!this->shares.empty());
4802 SharesMap::const_iterator it = this->shares.upper_bound(RandomRange(this->unrestricted));
4803 assert(it != this->shares.end() && it->first <= this->unrestricted);
4804 if (it->second != excluded && it->second != excluded2) return it->second;
4805
4806 /* We've hit one of the excluded stations.
4807 * Draw another share, from outside its range. */
4808
4809 uint end = it->first;
4810 uint begin = (it == this->shares.begin() ? 0 : (--it)->first);
4811 uint interval = end - begin;
4812 if (interval >= this->unrestricted) return INVALID_STATION; // Only one station in the map.
4813 uint new_max = this->unrestricted - interval;
4814 uint rand = RandomRange(new_max);
4815 SharesMap::const_iterator it2 = (rand < begin) ? this->shares.upper_bound(rand) :
4816 this->shares.upper_bound(rand + interval);
4817 assert(it2 != this->shares.end() && it2->first <= this->unrestricted);
4818 if (it2->second != excluded && it2->second != excluded2) return it2->second;
4819
4820 /* We've hit the second excluded station.
4821 * Same as before, only a bit more complicated. */
4822
4823 uint end2 = it2->first;
4824 uint begin2 = (it2 == this->shares.begin() ? 0 : (--it2)->first);
4825 uint interval2 = end2 - begin2;
4826 if (interval2 >= new_max) return INVALID_STATION; // Only the two excluded stations in the map.
4827 new_max -= interval2;
4828 if (begin > begin2) {
4829 Swap(begin, begin2);
4830 Swap(end, end2);
4831 Swap(interval, interval2);
4832 }
4833 rand = RandomRange(new_max);
4834 SharesMap::const_iterator it3 = this->shares.upper_bound(this->unrestricted);
4835 if (rand < begin) {
4836 it3 = this->shares.upper_bound(rand);
4837 } else if (rand < begin2 - interval) {
4838 it3 = this->shares.upper_bound(rand + interval);
4839 } else {
4840 it3 = this->shares.upper_bound(rand + interval + interval2);
4841 }
4842 assert(it3 != this->shares.end() && it3->first <= this->unrestricted);
4843 return it3->second;
4844}
4845
4851 void FlowStat::Invalidate()
4852{
4853 assert(!this->shares.empty());
4854 SharesMap new_shares;
4855 uint i = 0;
4856 for (const auto &it : this->shares) {
4857 new_shares[++i] = it.second;
4858 if (it.first == this->unrestricted) this->unrestricted = i;
4859 }
4860 this->shares.swap(new_shares);
4861 assert(!this->shares.empty() && this->unrestricted <= (--this->shares.end())->first);
4862}
4863
4870 void FlowStat::ChangeShare(StationID st, int flow)
4871{
4872 /* We assert only before changing as afterwards the shares can actually
4873 * be empty. In that case the whole flow stat must be deleted then. */
4874 assert(!this->shares.empty());
4875
4876 uint removed_shares = 0;
4877 uint added_shares = 0;
4878 uint last_share = 0;
4879 SharesMap new_shares;
4880 for (const auto &it : this->shares) {
4881 if (it.second == st) {
4882 if (flow < 0) {
4883 uint share = it.first - last_share;
4884 if (flow == INT_MIN || (uint)(-flow) >= share) {
4885 removed_shares += share;
4886 if (it.first <= this->unrestricted) this->unrestricted -= share;
4887 if (flow != INT_MIN) flow += share;
4888 last_share = it.first;
4889 continue; // remove the whole share
4890 }
4891 removed_shares += (uint)(-flow);
4892 } else {
4893 added_shares += (uint)(flow);
4894 }
4895 if (it.first <= this->unrestricted) this->unrestricted += flow;
4896
4897 /* If we don't continue above the whole flow has been added or
4898 * removed. */
4899 flow = 0;
4900 }
4901 new_shares[it.first + added_shares - removed_shares] = it.second;
4902 last_share = it.first;
4903 }
4904 if (flow > 0) {
4905 new_shares[last_share + (uint)flow] = st;
4906 if (this->unrestricted < last_share) {
4907 this->ReleaseShare(st);
4908 } else {
4909 this->unrestricted += flow;
4910 }
4911 }
4912 this->shares.swap(new_shares);
4913}
4914
4920 void FlowStat::RestrictShare(StationID st)
4921{
4922 assert(!this->shares.empty());
4923 uint flow = 0;
4924 uint last_share = 0;
4925 SharesMap new_shares;
4926 for (auto &it : this->shares) {
4927 if (flow == 0) {
4928 if (it.first > this->unrestricted) return; // Not present or already restricted.
4929 if (it.second == st) {
4930 flow = it.first - last_share;
4931 this->unrestricted -= flow;
4932 } else {
4933 new_shares[it.first] = it.second;
4934 }
4935 } else {
4936 new_shares[it.first - flow] = it.second;
4937 }
4938 last_share = it.first;
4939 }
4940 if (flow == 0) return;
4941 new_shares[last_share + flow] = st;
4942 this->shares.swap(new_shares);
4943 assert(!this->shares.empty());
4944}
4945
4951 void FlowStat::ReleaseShare(StationID st)
4952{
4953 assert(!this->shares.empty());
4954 uint flow = 0;
4955 uint next_share = 0;
4956 bool found = false;
4957 for (SharesMap::reverse_iterator it(this->shares.rbegin()); it != this->shares.rend(); ++it) {
4958 if (it->first < this->unrestricted) return; // Note: not <= as the share may hit the limit.
4959 if (found) {
4960 flow = next_share - it->first;
4961 this->unrestricted += flow;
4962 break;
4963 } else {
4964 if (it->first == this->unrestricted) return; // !found -> Limit not hit.
4965 if (it->second == st) found = true;
4966 }
4967 next_share = it->first;
4968 }
4969 if (flow == 0) return;
4970 SharesMap new_shares;
4971 new_shares[flow] = st;
4972 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4973 if (it->second != st) {
4974 new_shares[flow + it->first] = it->second;
4975 } else {
4976 flow = 0;
4977 }
4978 }
4979 this->shares.swap(new_shares);
4980 assert(!this->shares.empty());
4981}
4982
4988 void FlowStat::ScaleToMonthly(uint runtime)
4989{
4990 assert(runtime > 0);
4991 SharesMap new_shares;
4992 uint share = 0;
4993 for (auto i : this->shares) {
4994 share = std::max(share + 1, i.first * 30 / runtime);
4995 new_shares[share] = i.second;
4996 if (this->unrestricted == i.first) this->unrestricted = share;
4997 }
4998 this->shares.swap(new_shares);
4999}
5000
5007 void FlowStatMap::AddFlow(StationID origin, StationID via, uint flow)
5008{
5009 FlowStatMap::iterator origin_it = this->find(origin);
5010 if (origin_it == this->end()) {
5011 this->emplace(origin, FlowStat(via, flow));
5012 } else {
5013 origin_it->second.ChangeShare(via, flow);
5014 assert(!origin_it->second.GetShares()->empty());
5015 }
5016}
5017
5026 void FlowStatMap::PassOnFlow(StationID origin, StationID via, uint flow)
5027{
5028 FlowStatMap::iterator prev_it = this->find(origin);
5029 if (prev_it == this->end()) {
5030 FlowStat fs(via, flow);
5031 fs.AppendShare(INVALID_STATION, flow);
5032 this->emplace(origin, fs);
5033 } else {
5034 prev_it->second.ChangeShare(via, flow);
5035 prev_it->second.ChangeShare(INVALID_STATION, flow);
5036 assert(!prev_it->second.GetShares()->empty());
5037 }
5038}
5039
5044 void FlowStatMap::FinalizeLocalConsumption(StationID self)
5045{
5046 for (auto &i : *this) {
5047 FlowStat &fs = i.second;
5048 uint local = fs.GetShare(INVALID_STATION);
5049 if (local > INT_MAX) { // make sure it fits in an int
5050 fs.ChangeShare(self, -INT_MAX);
5051 fs.ChangeShare(INVALID_STATION, -INT_MAX);
5052 local -= INT_MAX;
5053 }
5054 fs.ChangeShare(self, -(int)local);
5055 fs.ChangeShare(INVALID_STATION, -(int)local);
5056
5057 /* If the local share is used up there must be a share for some
5058 * remote station. */
5059 assert(!fs.GetShares()->empty());
5060 }
5061}
5062
5069 StationIDStack FlowStatMap::DeleteFlows(StationID via)
5070{
5071 StationIDStack ret;
5072 for (FlowStatMap::iterator f_it = this->begin(); f_it != this->end();) {
5073 FlowStat &s_flows = f_it->second;
5074 s_flows.ChangeShare(via, INT_MIN);
5075 if (s_flows.GetShares()->empty()) {
5076 ret.Push(f_it->first);
5077 this->erase(f_it++);
5078 } else {
5079 ++f_it;
5080 }
5081 }
5082 return ret;
5083}
5084
5089 void FlowStatMap::RestrictFlows(StationID via)
5090{
5091 for (auto &it : *this) {
5092 it.second.RestrictShare(via);
5093 }
5094}
5095
5100 void FlowStatMap::ReleaseFlows(StationID via)
5101{
5102 for (auto &it : *this) {
5103 it.second.ReleaseShare(via);
5104 }
5105}
5106
5111uint FlowStatMap::GetFlow() const
5112{
5113 uint ret = 0;
5114 for (const auto &it : *this) {
5115 ret += (--(it.second.GetShares()->end()))->first;
5116 }
5117 return ret;
5118}
5119
5125uint FlowStatMap::GetFlowVia(StationID via) const
5126{
5127 uint ret = 0;
5128 for (const auto &it : *this) {
5129 ret += it.second.GetShare(via);
5130 }
5131 return ret;
5132}
5133
5139uint FlowStatMap::GetFlowFrom(StationID from) const
5140{
5141 FlowStatMap::const_iterator i = this->find(from);
5142 if (i == this->end()) return 0;
5143 return (--(i->second.GetShares()->end()))->first;
5144}
5145
5152uint FlowStatMap::GetFlowFromVia(StationID from, StationID via) const
5153{
5154 FlowStatMap::const_iterator i = this->find(from);
5155 if (i == this->end()) return 0;
5156 return i->second.GetShare(via);
5157}
5158
5159extern const TileTypeProcs _tile_type_station_procs = {
5160 DrawTile_Station, // draw_tile_proc
5161 GetSlopePixelZ_Station, // get_slope_z_proc
5162 ClearTile_Station, // clear_tile_proc
5163 nullptr, // add_accepted_cargo_proc
5164 GetTileDesc_Station, // get_tile_desc_proc
5165 GetTileTrackStatus_Station, // get_tile_track_status_proc
5166 ClickTile_Station, // click_tile_proc
5167 AnimateTile_Station, // animate_tile_proc
5168 TileLoop_Station, // tile_loop_proc
5169 ChangeTileOwner_Station, // change_tile_owner_proc
5170 nullptr, // add_produced_cargo_proc
5171 VehicleEnter_Station, // vehicle_enter_tile_proc
5172 GetFoundation_Station, // get_foundation_proc
5173 TerraformTile_Station, // terraform_tile_proc
5174};
aircraft.h
Base for aircraft.
UpdateAirplanesOnNewStation
void UpdateAirplanesOnNewStation(const Station *st)
Updates the status of the Aircraft heading or in the station.
Definition aircraft_cmd.cpp:2160
GetAirport
const AirportFTAClass * GetAirport(const uint8_t airport_type)
Get the finite state machine of an airport type.
Definition airport.cpp:207
INVALID_AIRPORTTILE
static const uint INVALID_AIRPORTTILE
id for an invalid airport tile
Definition airport.h:25
NEW_AIRPORTTILE_OFFSET
static const uint NEW_AIRPORTTILE_OFFSET
offset of first newgrf airport tile
Definition airport.h:24
NUM_AIRPORTS
@ NUM_AIRPORTS
Maximal number of airports in total.
Definition airport.h:41
AT_OILRIG
@ AT_OILRIG
Oilrig airport.
Definition airport.h:38
AIRPORT_CLOSED_block
static const uint64_t AIRPORT_CLOSED_block
Dummy block for indicating a closed airport.
Definition airport.h:128
FLYING
@ FLYING
Vehicle is flying in the air.
Definition airport.h:75
airporttile_ids.h
Enum of the default airport tiles.
AddAnimatedTile
void AddAnimatedTile(TileIndex tile, bool mark_dirty)
Add the given tile to the animated tile table (if it does not exist yet).
Definition animated_tile.cpp:56
DeleteAnimatedTile
void DeleteAnimatedTile(TileIndex tile, bool immediate)
Stops animation on the given tile.
Definition animated_tile.cpp:27
animated_tile_func.h
Tile animation!
autoslope.h
Functions related to autoslope.
AutoslopeCheckForAxis
bool AutoslopeCheckForAxis(TileIndex tile, int z_new, Slope tileh_new, Axis axis)
Autoslope check for tiles with something built along an axis.
Definition autoslope.h:51
AutoslopeCheckForEntranceEdge
bool AutoslopeCheckForEntranceEdge(TileIndex tile, int z_new, Slope tileh_new, DiagDirection entrance)
Autoslope check for tiles with an entrance on an edge.
Definition autoslope.h:31
AutoslopeEnabled
bool AutoslopeEnabled()
Tests if autoslope is enabled for _current_company.
Definition autoslope.h:65
HasBit
debug_inline constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
Definition bitmath_func.hpp:103
HasExactlyOneBit
constexpr bool HasExactlyOneBit(T value)
Test whether value has exactly 1 bit set.
Definition bitmath_func.hpp:278
SB
constexpr T SB(T &x, const uint8_t s, const uint8_t n, const U d)
Set n bits in x starting at bit s to d.
Definition bitmath_func.hpp:58
SetBit
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
Definition bitmath_func.hpp:121
FindFirstBit
constexpr uint8_t FindFirstBit(T x)
Search the first set bit in a value.
Definition bitmath_func.hpp:213
CountBits
constexpr uint CountBits(T value)
Counts the number of set bits in a variable.
Definition bitmath_func.hpp:262
GB
debug_inline static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
Definition bitmath_func.hpp:32
ClrBit
constexpr T ClrBit(T &x, const uint8_t y)
Clears a bit in a variable.
Definition bitmath_func.hpp:151
bridge_map.h
Map accessor functions for bridges.
IsBridgeAbove
bool IsBridgeAbove(Tile t)
checks if a bridge is set above the ground of this tile
Definition bridge_map.h:45
CargoID
uint8_t CargoID
Cargo slots to indicate a cargo type within a game.
Definition cargo_type.h:22
IsValidCargoID
bool IsValidCargoID(CargoID t)
Test whether cargo type is not INVALID_CARGO.
Definition cargo_type.h:107
SourceID
uint16_t SourceID
Contains either industry ID, town ID or company ID (or INVALID_SOURCE)
Definition cargo_type.h:143
NUM_CARGO
static const CargoID NUM_CARGO
Maximum number of cargo types in a game.
Definition cargo_type.h:74
SourceType
SourceType
Types of cargo source and destination.
Definition cargo_type.h:137
IsCargoInClass
bool IsCargoInClass(CargoID c, CargoClass cc)
Does cargo c have cargo class cc?
Definition cargotype.h:239
CC_MAIL
@ CC_MAIL
Mail.
Definition cargotype.h:51
CC_LIQUID
@ CC_LIQUID
Liquids (Oil, Water, Rubber)
Definition cargotype.h:56
CC_PASSENGERS
@ CC_PASSENGERS
Passengers.
Definition cargotype.h:50
_cheats
Cheats _cheats
All the cheats.
Definition cheat.cpp:16
cheat_type.h
Types related to cheating.
AirportTileIterator
Iterator to iterate over all tiles belonging to an airport.
Definition station_base.h:525
AirportTileTableIterator
Iterator to iterate over all tiles belonging to an airport spec.
Definition newgrf_airport.h:31
BitmapTileIterator
Iterator to iterate over all tiles belonging to a bitmaptilearea.
Definition bitmap_type.h:106
CargoList::Packets
const Tcont * Packets() const
Returns a pointer to the cargo packet list (so you can iterate over it etc).
Definition cargopacket.h:329
CommandCost
Common return value for all commands.
Definition command_type.h:23
CommandCost::Succeeded
bool Succeeded() const
Did this command succeed?
Definition command_type.h:162
CommandCost::AddCost
void AddCost(const Money &cost)
Adds the given cost to the cost of the command.
Definition command_type.h:63
CommandCost::Failed
bool Failed() const
Did this command fail?
Definition command_type.h:171
FlowStatMap::GetFlow
uint GetFlow() const
Get the sum of all flows from this FlowStatMap.
Definition station_cmd.cpp:5111
FlowStatMap::PassOnFlow
void PassOnFlow(StationID origin, StationID via, uint amount)
Pass on some flow, remembering it as invalid, for later subtraction from locally consumed flow.
Definition station_cmd.cpp:5026
FlowStatMap::AddFlow
void AddFlow(StationID origin, StationID via, uint amount)
Add some flow from "origin", going via "via".
Definition station_cmd.cpp:5007
FlowStatMap::GetFlowFrom
uint GetFlowFrom(StationID from) const
Get the sum of flows from a specific station from this FlowStatMap.
Definition station_cmd.cpp:5139
FlowStatMap::FinalizeLocalConsumption
void FinalizeLocalConsumption(StationID self)
Subtract invalid flows from locally consumed flow.
Definition station_cmd.cpp:5044
FlowStatMap::ReleaseFlows
void ReleaseFlows(StationID via)
Release all flows at a station for specific cargo and destination.
Definition station_cmd.cpp:5100
FlowStatMap::DeleteFlows
StationIDStack DeleteFlows(StationID via)
Delete all flows at a station for specific cargo and destination.
Definition station_cmd.cpp:5069
FlowStatMap::GetFlowFromVia
uint GetFlowFromVia(StationID from, StationID via) const
Get the flow from a specific station via a specific other station.
Definition station_cmd.cpp:5152
FlowStatMap::GetFlowVia
uint GetFlowVia(StationID via) const
Get the sum of flows via a specific station from this FlowStatMap.
Definition station_cmd.cpp:5125
FlowStatMap::RestrictFlows
void RestrictFlows(StationID via)
Restrict all flows at a station for specific cargo and destination.
Definition station_cmd.cpp:5089
FlowStat
Flow statistics telling how much flow should be sent along a link.
Definition station_base.h:32
FlowStat::empty_sharesmap
static const SharesMap empty_sharesmap
Static instance of FlowStat::SharesMap.
Definition station_base.h:36
FlowStat::ScaleToMonthly
void ScaleToMonthly(uint runtime)
Scale all shares from link graph's runtime to monthly values.
Definition station_cmd.cpp:4988
FlowStat::RestrictShare
void RestrictShare(StationID st)
Restrict a flow by moving it to the end of the map and decreasing the amount of unrestricted flow.
Definition station_cmd.cpp:4920
FlowStat::GetShare
uint GetShare(StationID st) const
Get flow for a station.
Definition station_cmd.cpp:4779
FlowStat::GetVia
StationID GetVia() const
Get a station a package can be routed to.
Definition station_base.h:130
FlowStat::GetShares
const SharesMap * GetShares() const
Get the actual shares as a const pointer so that they can be iterated over.
Definition station_base.h:88
FlowStat::shares
SharesMap shares
Shares of flow to be sent via specified station (or consumed locally).
Definition station_base.h:143
FlowStat::ReleaseShare
void ReleaseShare(StationID st)
Release ("unrestrict") a flow by moving it to the begin of the map and increasing the amount of unres...
Definition station_cmd.cpp:4951
FlowStat::ChangeShare
void ChangeShare(StationID st, int flow)
Change share for specified station.
Definition station_cmd.cpp:4870
FlowStat::AppendShare
void AppendShare(StationID st, uint flow, bool restricted=false)
Add some flow to the end of the shares map.
Definition station_base.h:66
FlowStat::Invalidate
void Invalidate()
Reduce all flows to minimum capacity so that they don't get in the way of link usage statistics too m...
Definition station_cmd.cpp:4851
FlowStat::unrestricted
uint unrestricted
Limit for unrestricted shares.
Definition station_base.h:144
IntervalTimer
An interval timer will fire every interval, and will continue to fire until it is deleted.
Definition timer.h:76
Kdtree::Insert
void Insert(const T &element)
Insert a single element in the tree.
Definition kdtree.hpp:398
Kdtree::Remove
void Remove(const T &element)
Remove a single element from the tree, if it exists.
Definition kdtree.hpp:417
LinkGraphSchedule::instance
static LinkGraphSchedule instance
Static instance of LinkGraphSchedule.
Definition linkgraphschedule.h:52
LinkGraphSchedule::Unqueue
void Unqueue(LinkGraph *lg)
Remove a link graph from the execution queue.
Definition linkgraphschedule.h:77
LinkGraphSchedule::Queue
void Queue(LinkGraph *lg)
Queue a link graph for execution.
Definition linkgraphschedule.h:67
LinkGraph
A connected component of a link graph.
Definition linkgraph.h:37
LinkGraph::Merge
void Merge(LinkGraph *other)
Merge a link graph with another one.
Definition linkgraph.cpp:90
LinkGraph::LastCompression
TimerGameEconomy::Date LastCompression() const
Get date of last compression.
Definition linkgraph.h:236
LinkGraph::AddNode
NodeID AddNode(const Station *st)
Add a node to the component and create empty edges associated with it.
Definition linkgraph.cpp:149
LinkGraph::Size
NodeID Size() const
Get the current size of the component.
Definition linkgraph.h:230
LinkGraph::MIN_TIMEOUT_DISTANCE
static const uint MIN_TIMEOUT_DISTANCE
Minimum effective distance for timeout calculation.
Definition linkgraph.h:170
LinkGraph::STALE_LINK_DEPOT_TIMEOUT
static constexpr TimerGameEconomy::Date STALE_LINK_DEPOT_TIMEOUT
Number of days before deleting links served only by vehicles stopped in depot.
Definition linkgraph.h:173
LinkGraph::COMPRESSION_INTERVAL
static constexpr TimerGameEconomy::Date COMPRESSION_INTERVAL
Minimum number of days between subsequent compressions of a LG.
Definition linkgraph.h:176
LinkRefresher::Run
static void Run(Vehicle *v, bool allow_merge=true, bool is_full_loading=false)
Refresh all links the given vehicle will visit.
Definition refresh.cpp:26
MultiMap::MapSize
size_t MapSize() const
Count the number of ranges with equal keys in this MultiMap.
Definition multimap.hpp:347
NewGRFClass
Struct containing information relating to NewGRF classes for stations and airports.
Definition newgrf_class.h:26
NewGRFClass::name
StringID name
Name of this class.
Definition newgrf_class.h:49
NewGRFClass::Get
static NewGRFClass * Get(Tindex class_index)
Get a particular class.
Definition newgrf_class_func.h:82
NewGRFClass::GetSpecCount
uint GetSpecCount() const
Get the number of allocated specs within the class.
Definition newgrf_class.h:70
NewGRFClass::GetClassCount
static uint GetClassCount()
Get the number of allocated classes.
Definition newgrf_class_func.h:93
NewGRFClass::GetSpec
const Tspec * GetSpec(uint index) const
Get a spec from the class at a given index.
Definition newgrf_class_func.h:114
OverflowSafeInt< int64_t >
RailTypeInfo
This struct contains all the info that is needed to draw and construct tracks.
Definition rail.h:127
RailTypeInfo::single_x
SpriteID single_x
single piece of rail in X direction, without ground
Definition rail.h:137
RailTypeInfo::max_speed
uint16_t max_speed
Maximum speed for vehicles travelling on this rail type.
Definition rail.h:231
RailTypeInfo::base_sprites
struct RailTypeInfo::@23 base_sprites
Struct containing the main sprites.
RailTypeInfo::strings
struct RailTypeInfo::@26 strings
Strings associated with the rail type.
RailTypeInfo::name
StringID name
Name of this rail type.
Definition rail.h:176
RailTypeInfo::fallback_railtype
uint8_t fallback_railtype
Original railtype number to use when drawing non-newgrf railtypes, or when drawing stations.
Definition rail.h:201
RailTypeInfo::GetRailtypeSpriteOffset
uint GetRailtypeSpriteOffset() const
Offset between the current railtype and normal rail.
Definition rail.h:295
RoadTypeInfo
Definition road.h:78
RoadTypeInfo::strings
struct RoadTypeInfo::@29 strings
Strings associated with the rail type.
RoadTypeInfo::max_speed
uint16_t max_speed
Maximum speed for vehicles travelling on this road type.
Definition road.h:142
RoadTypeInfo::name
StringID name
Name of this rail type.
Definition road.h:103
SmallStack
Minimal stack that uses a pool to avoid pointers.
Definition smallstack_type.hpp:135
SmallStack::Push
void Push(const Titem &item)
Pushes a new item onto the stack if there is still space in the underlying pool.
Definition smallstack_type.hpp:192
StationCargoList::Reroute
uint Reroute(uint max_move, StationCargoList *dest, StationID avoid, StationID avoid2, const GoodsEntry *ge)
Routes packets with station "avoid" as next hop to a different place.
Definition cargopacket.cpp:856
StationCargoList::AvailableCount
uint AvailableCount() const
Returns sum of cargo still available for loading at the sation.
Definition cargopacket.h:588
StationCargoList::Append
void Append(CargoPacket *cp, StationID next)
Appends the given cargo packet to the range of packets with the same next station.
Definition cargopacket.cpp:686
StationCargoList::Truncate
uint Truncate(uint max_move=UINT_MAX, StationCargoAmountMap *cargo_per_source=nullptr)
Truncates where each destination loses roughly the same percentage of its cargo.
Definition cargopacket.cpp:765
StationFinder::GetStations
const StationList & GetStations()
Run a tile loop to find stations around a tile, on demand.
Definition station_cmd.cpp:4354
StationFinder::stations
StationList stations
List of stations nearby.
Definition station_type.h:101
Ticks::STATION_LINKGRAPH_TICKS
static constexpr TimerGameTick::Ticks STATION_LINKGRAPH_TICKS
Cycle duration for cleaning dead links.
Definition timer_game_tick.h:80
Ticks::STATION_ACCEPTANCE_TICKS
static constexpr TimerGameTick::Ticks STATION_ACCEPTANCE_TICKS
Cycle duration for updating station acceptance.
Definition timer_game_tick.h:79
Ticks::STATION_RATING_TICKS
static constexpr TimerGameTick::Ticks STATION_RATING_TICKS
Cycle duration for updating station rating.
Definition timer_game_tick.h:78
TileIterator
Base class for tile iterators.
Definition tilearea_type.h:105
Tile
Wrapper class to abstract away the way the tiles are stored.
Definition map_func.h:25
TimerGameCalendar::date
static Date date
Current date in days (day counter).
Definition timer_game_calendar.h:33
TimerGameConst< struct Economy >::INVALID_DATE
static constexpr TimerGame< struct Economy >::Date INVALID_DATE
Representation of an invalid date.
Definition timer_game_common.h:193
TimerGameEconomy::date
static Date date
Current date in days (day counter).
Definition timer_game_economy.h:38
TimerGameTick::counter
static TickCounter counter
Monotonic counter, in ticks, since start of game.
Definition timer_game_tick.h:60
VehicleCargoList::StoredCount
uint StoredCount() const
Returns sum of cargo on board the vehicle (ie not only reserved).
Definition cargopacket.h:434
clear_func.h
Functions related to clear (MP_CLEAR) land.
command_func.h
Functions related to commands.
CMD_ERROR
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
Definition command_func.h:28
DoCommandFlag
DoCommandFlag
List of flags for a command.
Definition command_type.h:374
DC_AUTO
@ DC_AUTO
don't allow building on structures
Definition command_type.h:377
DC_BANKRUPT
@ DC_BANKRUPT
company bankrupts, skip money check, skip vehicle on tile check in some cases
Definition command_type.h:382
DC_EXEC
@ DC_EXEC
execute the given command
Definition command_type.h:376
company_base.h
Definition of stuff that is very close to a company, like the company struct itself.
CheckOwnership
CommandCost CheckOwnership(Owner owner, TileIndex tile)
Check whether the current owner owns something.
Definition company_cmd.cpp:363
_local_company
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Definition company_cmd.cpp:52
_current_company
CompanyID _current_company
Company currently doing an action.
Definition company_cmd.cpp:53
DirtyCompanyInfrastructureWindows
void DirtyCompanyInfrastructureWindows(CompanyID company)
Redraw all windows with company infrastructure counts.
Definition company_gui.cpp:2606
company_gui.h
GUI Functions related to companies.
Owner
Owner
Enum for all companies/owners.
Definition company_type.h:18
INVALID_OWNER
@ INVALID_OWNER
An invalid owner.
Definition company_type.h:29
OWNER_NONE
@ OWNER_NONE
The tile has no ownership.
Definition company_type.h:25
OWNER_WATER
@ OWNER_WATER
The tile/execution is done by "water".
Definition company_type.h:26
OWNER_TOWN
@ OWNER_TOWN
A town owns the tile, or a town is expanding.
Definition company_type.h:24
container_func.hpp
Some simple functions to help with accessing containers.
include
bool include(Container &container, typename Container::const_reference &item)
Helper function to append an item to a container if it is not already contained.
Definition container_func.hpp:24
debug.h
Functions related to debugging.
Debug
#define Debug(category, level, format_string,...)
Ouptut a line of debugging information.
Definition debug.h:37
CanBuildDepotByTileh
bool CanBuildDepotByTileh(DiagDirection direction, Slope tileh)
Find out if the slope of the tile is suitable to build a depot of given direction.
Definition depot_func.h:27
ShowDepotWindow
void ShowDepotWindow(TileIndex tile, VehicleType type)
Opens a depot window.
Definition depot_gui.cpp:1164
IsValidAxis
bool IsValidAxis(Axis d)
Checks if an integer value is a valid Axis.
Definition direction_func.h:43
ReverseDiagDir
DiagDirection ReverseDiagDir(DiagDirection d)
Returns the reverse direction of the given DiagDirection.
Definition direction_func.h:118
IsValidDiagDirection
bool IsValidDiagDirection(DiagDirection d)
Checks if an integer value is a valid DiagDirection.
Definition direction_func.h:21
AxisToDiagDir
DiagDirection AxisToDiagDir(Axis a)
Converts an Axis to a DiagDirection.
Definition direction_func.h:232
OtherAxis
Axis OtherAxis(Axis a)
Select the other axis as provided.
Definition direction_func.h:197
DiagDirToAxis
Axis DiagDirToAxis(DiagDirection d)
Convert a DiagDirection to the axis.
Definition direction_func.h:214
DirToDiagDir
DiagDirection DirToDiagDir(Direction dir)
Convert a Direction to a DiagDirection.
Definition direction_func.h:166
Direction
Direction
Defines the 8 directions on the map.
Definition direction_type.h:24
DIR_W
@ DIR_W
West.
Definition direction_type.h:32
DIR_E
@ DIR_E
East.
Definition direction_type.h:28
Axis
Axis
Allow incrementing of DiagDirDiff variables.
Definition direction_type.h:116
AXIS_X
@ AXIS_X
The X axis.
Definition direction_type.h:117
DiagDirection
DiagDirection
Enumeration for diagonal directions.
Definition direction_type.h:73
DIAGDIR_NE
@ DIAGDIR_NE
Northeast, upper right on your monitor.
Definition direction_type.h:75
DIAGDIR_SE
@ DIAGDIR_SE
Southeast.
Definition direction_type.h:76
DIAGDIR_END
@ DIAGDIR_END
Used for iterations.
Definition direction_type.h:79
DIAGDIR_BEGIN
@ DIAGDIR_BEGIN
Used for iterations.
Definition direction_type.h:74
INVALID_DIAGDIR
@ INVALID_DIAGDIR
Flag for an invalid DiagDirection.
Definition direction_type.h:80
DIAGDIR_SW
@ DIAGDIR_SW
Southwest.
Definition direction_type.h:77
ROAD_STOP_TRACKBIT_FACTOR
static const uint ROAD_STOP_TRACKBIT_FACTOR
Multiplier for how many regular track bits a bay stop counts.
Definition economy_type.h:247
EXPENSES_CONSTRUCTION
@ EXPENSES_CONSTRUCTION
Construction costs.
Definition economy_type.h:173
Price
Price
Enumeration of all base prices for use with Prices.
Definition economy_type.h:89
DrawRailCatenary
void DrawRailCatenary(const TileInfo *ti)
Draws overhead wires and pylons for electric railways.
Definition elrail.cpp:568
elrail_func.h
header file for electrified rail specific functions
HasRailCatenaryDrawn
bool HasRailCatenaryDrawn(RailType rt)
Test if we should draw rail catenary.
Definition elrail_func.h:30
HasFlag
debug_inline constexpr bool HasFlag(const T x, const T y)
Checks if a value in a bitset enum is set.
Definition enum_type.hpp:58
DrawSprite
void DrawSprite(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub, ZoomLevel zoom)
Draw a sprite, not in a viewport.
Definition gfx.cpp:988
SpriteID
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition gfx_type.h:18
PaletteID
uint32_t PaletteID
The number of the palette.
Definition gfx_type.h:19
GetSnowLine
uint8_t GetSnowLine()
Get the current snow line, either variable or static.
Definition landscape.cpp:609
Station::MarkTilesDirty
void MarkTilesDirty(bool cargo_change) const
Marks the tiles of the station as dirty.
Definition station.cpp:243
MarkTileDirtyByTile
void MarkTileDirtyByTile(TileIndex tile, int bridge_level_offset, int tile_height_override)
Mark a tile given by its index dirty for repaint.
Definition viewport.cpp:2057
industry.h
Base of all industries.
IsTileForestIndustry
bool IsTileForestIndustry(TileIndex tile)
Check whether the tile is a forest.
Definition industry_cmd.cpp:977
GetIndustrySpec
const IndustrySpec * GetIndustrySpec(IndustryType thistype)
Accessor for array _industry_specs.
Definition industry_cmd.cpp:123
GetIndustryType
IndustryType GetIndustryType(Tile tile)
Retrieve the type for this industry.
Definition industry_cmd.cpp:106
GetIndustryIndex
IndustryID GetIndustryIndex(Tile t)
Get the industry ID of the given tile.
Definition industry_map.h:63
NUM_INDUSTRYTYPES
static const IndustryType NUM_INDUSTRYTYPES
total number of industry types, new and old; limited to 240 because we need some special ids like INV...
Definition industry_type.h:26
INDUSTRYLIFE_EXTRACTIVE
@ INDUSTRYLIFE_EXTRACTIVE
Like mines.
Definition industrytype.h:24
ChangeTileOwner
void ChangeTileOwner(TileIndex tile, Owner old_owner, Owner new_owner)
Change the owner of a tile.
Definition landscape.cpp:565
DrawFoundation
void DrawFoundation(TileInfo *ti, Foundation f)
Draw foundation f at tile ti.
Definition landscape.cpp:425
GetFoundationPixelSlope
std::tuple< Slope, int > GetFoundationPixelSlope(TileIndex tile)
Get slope of a tile on top of a (possible) foundation If a tile does not have a foundation,...
Definition landscape.h:65
ApplyPixelFoundationToSlope
uint ApplyPixelFoundationToSlope(Foundation f, Slope &s)
Applies a foundation to a slope.
Definition landscape.h:126
RemapCoords2
Point RemapCoords2(int x, int y)
Map 3D world or tile coordinate to equivalent 2D coordinate as used in the viewports and smallmap.
Definition landscape.h:95
landscape_cmd.h
Command definitions related to landscape (slopes etc.).
linkgraph_base.h
Some typedefs for the main game.
DT_MANUAL
@ DT_MANUAL
Manual distribution. No link graph calculations are run.
Definition linkgraph_type.h:25
EdgeUpdateMode
EdgeUpdateMode
Special modes for updating links.
Definition linkgraph_type.h:47
EUM_INCREASE
@ EUM_INCREASE
Increase capacity.
Definition linkgraph_type.h:48
CircularTileSearch
bool CircularTileSearch(TileIndex *tile, uint size, TestTileOnSearchProc proc, void *user_data)
Function performing a search around a center tile and going outward, thus in circle.
Definition map.cpp:247
DistanceFromEdge
uint DistanceFromEdge(TileIndex tile)
Param the minimum distance to an edge.
Definition map.cpp:206
DistanceMax
uint DistanceMax(TileIndex t0, TileIndex t1)
Gets the biggest distance component (x or y) between the two given tiles.
Definition map.cpp:178
TileAddWrap
TileIndex TileAddWrap(TileIndex tile, int addx, int addy)
This function checks if we add addx/addy to tile, if we do wrap around the edges.
Definition map.cpp:97
DistanceManhattan
uint DistanceManhattan(TileIndex t0, TileIndex t1)
Gets the Manhattan distance between the two given tiles.
Definition map.cpp:146
TileXY
static debug_inline TileIndex TileXY(uint x, uint y)
Returns the TileIndex of a coordinate.
Definition map_func.h:373
ToTileIndexDiff
TileIndexDiff ToTileIndexDiff(TileIndexDiffC tidc)
Return the offset between two tiles from a TileIndexDiffC struct.
Definition map_func.h:440
TileDiffXY
TileIndexDiff TileDiffXY(int x, int y)
Calculates an offset for the given coordinate(-offset).
Definition map_func.h:389
TileOffsByAxis
TileIndexDiff TileOffsByAxis(Axis axis)
Convert an Axis to a TileIndexDiff.
Definition map_func.h:552
TileY
static debug_inline uint TileY(TileIndex tile)
Get the Y component of a tile.
Definition map_func.h:425
TileX
static debug_inline uint TileX(TileIndex tile)
Get the X component of a tile.
Definition map_func.h:415
TileOffsByDiagDir
TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
Convert a DiagDirection to a TileIndexDiff.
Definition map_func.h:567
TileIndexDiff
int32_t TileIndexDiff
An offset value between two tiles.
Definition map_type.h:23
IsInsideBS
constexpr bool IsInsideBS(const T x, const size_t base, const size_t size)
Checks if a value is between a window started at some base point.
Definition math_func.hpp:252
Clamp
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition math_func.hpp:79
ClampU
constexpr uint ClampU(const uint a, const uint min, const uint max)
Clamp an unsigned integer between an interval.
Definition math_func.hpp:150
Swap
constexpr void Swap(T &a, T &b)
Type safe swap operation.
Definition math_func.hpp:283
StationGfx
uint8_t StationGfx
Copy from station_map.h.
Definition newgrf_airport.h:22
GetTranslatedAirportTileID
StationGfx GetTranslatedAirportTileID(StationGfx gfx)
Do airporttile gfx ID translation for NewGRFs.
Definition newgrf_airporttiles.cpp:96
newgrf_airporttiles.h
NewGRF handling of airport tiles.
AAT_BUILT
@ AAT_BUILT
Triggered when the airport is built (for all tiles at the same time).
Definition newgrf_animation_type.h:47
AAT_STATION_NEW_CARGO
@ AAT_STATION_NEW_CARGO
Triggered when new cargo arrives at the station (for all tiles at the same time).
Definition newgrf_animation_type.h:49
AAT_TILELOOP
@ AAT_TILELOOP
Triggered in the periodic tile loop.
Definition newgrf_animation_type.h:48
AAT_STATION_250_TICKS
@ AAT_STATION_250_TICKS
Triggered every 250 ticks (for all tiles at the same time).
Definition newgrf_animation_type.h:51
ANIM_STATUS_NO_ANIMATION
static const uint8_t ANIM_STATUS_NO_ANIMATION
There is no animation.
Definition newgrf_animation_type.h:15
SAT_NEW_CARGO
@ SAT_NEW_CARGO
Trigger station on new cargo arrival.
Definition newgrf_animation_type.h:28
SAT_BUILT
@ SAT_BUILT
Trigger tile when built.
Definition newgrf_animation_type.h:27
SAT_250_TICKS
@ SAT_250_TICKS
Trigger station every 250 ticks.
Definition newgrf_animation_type.h:33
CBM_STATION_DRAW_TILE_LAYOUT
@ CBM_STATION_DRAW_TILE_LAYOUT
Use callback to select a tile layout to use when drawing.
Definition newgrf_callbacks.h:318
CBM_STATION_SLOPE_CHECK
@ CBM_STATION_SLOPE_CHECK
Check slope of new station tiles.
Definition newgrf_callbacks.h:321
CBM_STATION_AVAIL
@ CBM_STATION_AVAIL
Availability of station in construction window.
Definition newgrf_callbacks.h:317
CBID_STATION_BUILD_TILE_LAYOUT
@ CBID_STATION_BUILD_TILE_LAYOUT
Called when building a station to customize the tile layout.
Definition newgrf_callbacks.h:96
CBID_STATION_DRAW_TILE_LAYOUT
@ CBID_STATION_DRAW_TILE_LAYOUT
Choose a tile layout to draw, instead of the standard range.
Definition newgrf_callbacks.h:42
CBID_CARGO_STATION_RATING_CALC
@ CBID_CARGO_STATION_RATING_CALC
Called to calculate part of a station rating.
Definition newgrf_callbacks.h:200
CBID_STATION_AVAILABILITY
@ CBID_STATION_AVAILABILITY
Determine whether a newstation should be made available to build.
Definition newgrf_callbacks.h:39
CBM_ROAD_STOP_AVAIL
@ CBM_ROAD_STOP_AVAIL
Availability of road stop in construction window.
Definition newgrf_callbacks.h:328
CALLBACK_FAILED
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
Definition newgrf_callbacks.h:427
CBM_CARGO_STATION_RATING_CALC
@ CBM_CARGO_STATION_RATING_CALC
custom station rating for this cargo type
Definition newgrf_callbacks.h:364
GetCanalSprite
SpriteID GetCanalSprite(CanalFeature feature, TileIndex tile)
Lookup the base sprite to use for a canal.
Definition newgrf_canal.cpp:140
newgrf_canal.h
Handling of NewGRF canals.
newgrf_cargo.h
Cargo support for NewGRFs.
ErrorUnknownCallbackResult
void ErrorUnknownCallbackResult(uint32_t grfid, uint16_t cbid, uint16_t cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
Definition newgrf_commons.cpp:505
Convert8bitBooleanCallback
bool Convert8bitBooleanCallback(const GRFFile *grffile, uint16_t cbid, uint16_t cb_res)
Converts a callback result into a boolean.
Definition newgrf_commons.cpp:554
GetGRFConfig
GRFConfig * GetGRFConfig(uint32_t grfid, uint32_t mask)
Retrieve a NewGRF from the current config by its grfid.
Definition newgrf_config.cpp:696
newgrf_debug.h
Functions/types related to NewGRF debugging.
DeleteNewGRFInspectWindow
void DeleteNewGRFInspectWindow(GrfSpecFeature feature, uint index)
Delete inspect window for a given feature and index.
Definition newgrf_debug_gui.cpp:729
WatchedCargoCallback
void WatchedCargoCallback(TileIndex tile, CargoTypes trigger_cargoes)
Run watched cargo accepted callback for a house.
Definition newgrf_house.cpp:754
newgrf_house.h
Functions related to NewGRF houses.
GetCustomRailSprite
SpriteID GetCustomRailSprite(const RailTypeInfo *rti, TileIndex tile, RailTypeSpriteGroup rtsg, TileContext context, uint *num_results)
Get the sprite to draw for the given tile.
Definition newgrf_railtype.cpp:96
newgrf_railtype.h
NewGRF handling of rail types.
newgrf_roadstop.h
NewGRF definitions and structures for road stops.
RoadStopDrawMode
RoadStopDrawMode
Different draw modes to disallow rendering of some parts of the stop or road.
Definition newgrf_roadstop.h:61
ROADSTOP_DRAW_MODE_ROAD
@ ROADSTOP_DRAW_MODE_ROAD
Bay stops: Draw the road itself.
Definition newgrf_roadstop.h:63
ROADSTOP_DRAW_MODE_OVERLAY
@ ROADSTOP_DRAW_MODE_OVERLAY
Drive-through stops: Draw the road overlay, e.g. pavement.
Definition newgrf_roadstop.h:64
ROADSTOP_DRAW_MODE_WAYP_GROUND
@ ROADSTOP_DRAW_MODE_WAYP_GROUND
Waypoints: Draw the sprite layout ground tile (on top of the road)
Definition newgrf_roadstop.h:65
RSRT_NEW_CARGO
@ RSRT_NEW_CARGO
Trigger roadstop on arrival of new cargo.
Definition newgrf_roadstop.h:38
IsWaypointClass
bool IsWaypointClass(const RoadStopClass &cls)
Test if a RoadStopClass is the waypoint class.
Definition newgrf_roadstop.h:200
RoadStopClassID
RoadStopClassID
Definition newgrf_roadstop.h:28
ROADSTOPTYPE_FREIGHT
@ ROADSTOPTYPE_FREIGHT
This RoadStop is for freight (truck) stops.
Definition newgrf_roadstop.h:51
ROADSTOPTYPE_ALL
@ ROADSTOPTYPE_ALL
This RoadStop is for both types of station road stops.
Definition newgrf_roadstop.h:52
ROADSTOPTYPE_PASSENGER
@ ROADSTOPTYPE_PASSENGER
This RoadStop is for passenger (bus) stops.
Definition newgrf_roadstop.h:50
RSF_NO_CATENARY
@ RSF_NO_CATENARY
Do not show catenary.
Definition newgrf_roadstop.h:71
RSF_DRAW_MODE_REGISTER
@ RSF_DRAW_MODE_REGISTER
Read draw mode from register 0x100.
Definition newgrf_roadstop.h:76
RSF_DRIVE_THROUGH_ONLY
@ RSF_DRIVE_THROUGH_ONLY
Stop is drive-through only.
Definition newgrf_roadstop.h:72
GetCustomRoadSprite
SpriteID GetCustomRoadSprite(const RoadTypeInfo *rti, TileIndex tile, RoadTypeSpriteGroup rtsg, TileContext context, uint *num_results)
Get the sprite to draw for the given tile.
Definition newgrf_roadtype.cpp:101
newgrf_roadtype.h
NewGRF handling of road types.
GetRegister
uint32_t GetRegister(uint i)
Gets the value of a so-called newgrf "register".
Definition newgrf_spritegroup.h:29
AllocateSpecToStation
int AllocateSpecToStation(const StationSpec *statspec, BaseStation *st, bool exec)
Allocate a StationSpec to a Station.
Definition newgrf_station.cpp:685
GetPlatformInfo
uint32_t GetPlatformInfo(Axis axis, uint8_t tile, int platforms, int length, int x, int y, bool centred)
Evaluate a tile's position within a station, and return the result in a bit-stuffed format.
Definition newgrf_station.cpp:104
GetCustomStationRelocation
SpriteID GetCustomStationRelocation(const StationSpec *statspec, BaseStation *st, TileIndex tile, uint32_t var10)
Resolve sprites for drawing a station tile.
Definition newgrf_station.cpp:611
TriggerStationRandomisation
void TriggerStationRandomisation(Station *st, TileIndex trigger_tile, StationRandomTrigger trigger, CargoID cargo_type)
Trigger station randomisation.
Definition newgrf_station.cpp:919
GetCustomStationFoundationRelocation
SpriteID GetCustomStationFoundationRelocation(const StationSpec *statspec, BaseStation *st, TileIndex tile, uint layout, uint edge_info)
Resolve the sprites for custom station foundations.
Definition newgrf_station.cpp:628
DeallocateSpecFromStation
void DeallocateSpecFromStation(BaseStation *st, uint8_t specindex)
Deallocate a StationSpec from a Station.
Definition newgrf_station.cpp:727
PerformStationTileSlopeCheck
CommandCost PerformStationTileSlopeCheck(TileIndex north_tile, TileIndex cur_tile, const StationSpec *statspec, Axis axis, uint8_t plat_len, uint8_t numtracks)
Check the slope of a tile of a new station.
Definition newgrf_station.cpp:657
newgrf_station.h
Header file for NewGRF stations.
SSF_SEPARATE_GROUND
@ SSF_SEPARATE_GROUND
Use different sprite set for ground sprites.
Definition newgrf_station.h:97
SSF_CUSTOM_FOUNDATIONS
@ SSF_CUSTOM_FOUNDATIONS
Draw custom foundations.
Definition newgrf_station.h:100
SSF_EXTENDED_FOUNDATIONS
@ SSF_EXTENDED_FOUNDATIONS
Extended foundation block instead of simple.
Definition newgrf_station.h:101
GetStationLayoutKey
uint16_t GetStationLayoutKey(uint8_t platforms, uint8_t length)
Get the station layout key for a given station layout size.
Definition newgrf_station.h:189
SRT_NEW_CARGO
@ SRT_NEW_CARGO
Trigger station on new cargo arrival.
Definition newgrf_station.h:106
StationClassID
StationClassID
Definition newgrf_station.h:86
news_func.h
Functions related to news.
AddNewsItem
void AddNewsItem(StringID string, NewsType type, NewsFlag flags, NewsReferenceType reftype1=NR_NONE, uint32_t ref1=UINT32_MAX, NewsReferenceType reftype2=NR_NONE, uint32_t ref2=UINT32_MAX, std::unique_ptr< NewsAllocatedData > &&data=nullptr)
Add a new newsitem to be shown.
Definition news_gui.cpp:897
NT_ACCEPTANCE
@ NT_ACCEPTANCE
A type of cargo is (no longer) accepted.
Definition news_type.h:37
NR_STATION
@ NR_STATION
Reference station. Scroll to station when clicking on the news. Delete news when station is deleted.
Definition news_type.h:56
NF_INCOLOUR
@ NF_INCOLOUR
Bit value for coloured news.
Definition news_type.h:74
NF_SMALL
@ NF_SMALL
Small news item. (Information window with text and viewport)
Definition news_type.h:80
order_backup.h
Functions related to order backups.
GetTrainForReservation
Train * GetTrainForReservation(TileIndex tile, Track track)
Find the train which has reserved a specific path.
Definition pbs.cpp:330
SetRailStationPlatformReservation
void SetRailStationPlatformReservation(TileIndex start, DiagDirection dir, bool b)
Set the reservation for a complete station platform.
Definition pbs.cpp:57
pbs.h
PBS support routines.
ValParamRailType
bool ValParamRailType(const RailType rail)
Validate functions for rail building.
Definition rail.cpp:206
RTSG_GROUND
@ RTSG_GROUND
Main group of ground images.
Definition rail.h:52
RTSG_OVERLAY
@ RTSG_OVERLAY
Images for overlaying track.
Definition rail.h:51
RailBuildCost
Money RailBuildCost(RailType railtype)
Returns the cost of building the specified railtype.
Definition rail.h:375
HasPowerOnRail
bool HasPowerOnRail(RailType enginetype, RailType tiletype)
Checks if an engine of the given RailType got power on a tile with a given RailType.
Definition rail.h:335
RailTrackOffset
RailTrackOffset
Offsets for sprites within an overlay/underlay set.
Definition rail.h:70
RTO_Y
@ RTO_Y
Piece of rail in Y direction.
Definition rail.h:72
RTO_X
@ RTO_X
Piece of rail in X direction.
Definition rail.h:71
GetRailTypeInfo
const RailTypeInfo * GetRailTypeInfo(RailType railtype)
Returns a pointer to the Railtype information for a given railtype.
Definition rail.h:307
rail_cmd.h
Command definitions for rail.
GetRailType
RailType GetRailType(Tile t)
Gets the rail type of the given tile.
Definition rail_map.h:115
GetTrackBits
TrackBits GetTrackBits(Tile tile)
Gets the track bits of the given tile.
Definition rail_map.h:136
GetRailReservationTrackBits
TrackBits GetRailReservationTrackBits(Tile t)
Returns the reserved track bits of the tile.
Definition rail_map.h:194
HasSignals
bool HasSignals(Tile t)
Checks if a rail tile has signals.
Definition rail_map.h:72
IsPlainRailTile
static debug_inline bool IsPlainRailTile(Tile t)
Checks whether the tile is a rail tile or rail tile with signals.
Definition rail_map.h:60
RailType
RailType
Enumeration for all possible railtypes.
Definition rail_type.h:27
INVALID_RAILTYPE
@ INVALID_RAILTYPE
Flag for invalid railtype.
Definition rail_type.h:34
random_func.hpp
Pseudo random number generator.
RandomRange
uint32_t RandomRange(uint32_t limit, const std::source_location location=std::source_location::current())
Pick a random number between 0 and limit - 1, inclusive.
Definition random_func.hpp:88
refresh.h
Definition of link refreshing utility.
ValParamRoadType
bool ValParamRoadType(RoadType roadtype)
Validate functions for rail building.
Definition road.cpp:153
HasPowerOnRoad
bool HasPowerOnRoad(RoadType enginetype, RoadType tiletype)
Checks if an engine of the given RoadType got power on a tile with a given RoadType.
Definition road.h:242
GetRoadTypeInfo
const RoadTypeInfo * GetRoadTypeInfo(RoadType roadtype)
Returns a pointer to the Roadtype information for a given roadtype.
Definition road.h:227
ROTSG_OVERLAY
@ ROTSG_OVERLAY
Optional: Images for overlaying track.
Definition road.h:61
ROTSG_ROADSTOP
@ ROTSG_ROADSTOP
Required: Bay stop surface.
Definition road.h:70
ROTSG_GROUND
@ ROTSG_GROUND
Required: Main group of ground images.
Definition road.h:62
RoadBuildCost
Money RoadBuildCost(RoadType roadtype)
Returns the cost of building the specified roadtype.
Definition road.h:252
CheckAllowRemoveRoad
CommandCost CheckAllowRemoveRoad(TileIndex tile, RoadBits remove, Owner owner, RoadTramType rtt, DoCommandFlag flags, bool town_check)
Is it allowed to remove the given road bits from the given tile?
Definition road_cmd.cpp:262
DrawRoadGroundSprites
void DrawRoadGroundSprites(const TileInfo *ti, RoadBits road, RoadBits tram, const RoadTypeInfo *road_rti, const RoadTypeInfo *tram_rti, Roadside roadside, bool snow_or_desert)
Draw road ground sprites.
Definition road_cmd.cpp:1605
DrawRoadCatenary
void DrawRoadCatenary(const TileInfo *ti)
Draws the catenary for the given tile.
Definition road_cmd.cpp:1451
UpdateCompanyRoadInfrastructure
void UpdateCompanyRoadInfrastructure(RoadType rt, Owner o, int count)
Update road infrastructure counts for a company.
Definition road_cmd.cpp:190
DrawRoadOverlays
void DrawRoadOverlays(const TileInfo *ti, PaletteID pal, const RoadTypeInfo *road_rti, const RoadTypeInfo *tram_rti, uint road_offset, uint tram_offset, bool draw_underlay)
Draw road underlay and overlay sprites.
Definition road_cmd.cpp:1515
road_func.h
Functions related to roads.
AxisToRoadBits
RoadBits AxisToRoadBits(Axis a)
Create the road-part which belongs to the given Axis.
Definition road_func.h:111
road_internal.h
Functions used internally by the roads.
GetAnyRoadBits
RoadBits GetAnyRoadBits(Tile tile, RoadTramType rtt, bool straight_tunnel_bridge_entrance)
Returns the RoadBits on an arbitrary tile Special behaviour:
Definition road_map.cpp:33
SetRoadOwner
void SetRoadOwner(Tile t, RoadTramType rtt, Owner o)
Set the owner of a specific road type.
Definition road_map.h:251
IsNormalRoadTile
static debug_inline bool IsNormalRoadTile(Tile t)
Return whether a tile is a normal road tile.
Definition road_map.h:74
GetRoadBits
RoadBits GetRoadBits(Tile t, RoadTramType rtt)
Get the present road bits for a specific road type.
Definition road_map.h:128
MayHaveRoad
bool MayHaveRoad(Tile t)
Test whether a tile can have road/tram types.
Definition road_map.h:33
GetDisallowedRoadDirections
DisallowedRoadDirections GetDisallowedRoadDirections(Tile t)
Gets the disallowed directions.
Definition road_map.h:301
HasTileRoadType
bool HasTileRoadType(Tile t, RoadTramType rtt)
Check if a tile has a road or a tram road type.
Definition road_map.h:211
MakeRoadNormal
void MakeRoadNormal(Tile t, RoadBits bits, RoadType road_rt, RoadType tram_rt, TownID town, Owner road, Owner tram)
Make a normal road tile.
Definition road_map.h:635
GetAllRoadBits
RoadBits GetAllRoadBits(Tile tile)
Get all set RoadBits on the given tile.
Definition road_map.h:141
GetRoadOwner
Owner GetRoadOwner(Tile t, RoadTramType rtt)
Get the owner of a specific road type.
Definition road_map.h:234
Roadside
Roadside
The possible road side decorations.
Definition road_map.h:477
ROADSIDE_PAVED
@ ROADSIDE_PAVED
Road with paved sidewalks.
Definition road_map.h:480
ROADSIDE_BARREN
@ ROADSIDE_BARREN
Road on barren land.
Definition road_map.h:478
ROADSIDE_GRASS
@ ROADSIDE_GRASS
Road on grass.
Definition road_map.h:479
RoadBits
RoadBits
Enumeration for the road parts on a tile.
Definition road_type.h:52
ROAD_NONE
@ ROAD_NONE
No road-part is build.
Definition road_type.h:53
ROAD_Y
@ ROAD_Y
Full road along the y-axis (north-west + south-east)
Definition road_type.h:59
ROAD_X
@ ROAD_X
Full road along the x-axis (south-west + north-east)
Definition road_type.h:58
RoadType
RoadType
The different roadtypes we support.
Definition road_type.h:25
INVALID_ROADTYPE
@ INVALID_ROADTYPE
flag for invalid roadtype
Definition road_type.h:30
DRD_NONE
@ DRD_NONE
None of the directions are disallowed.
Definition road_type.h:74
roadstop_base.h
Base class for roadstops.
roadveh.h
Road vehicle states.
RVSB_IN_ROAD_STOP
@ RVSB_IN_ROAD_STOP
The vehicle is in a road stop.
Definition roadveh.h:49
RVSB_ROAD_STOP_TRACKDIR_MASK
@ RVSB_ROAD_STOP_TRACKDIR_MASK
Only bits 0 and 3 are used to encode the trackdir for road stops.
Definition roadveh.h:57
RVS_IN_DT_ROAD_STOP
@ RVS_IN_DT_ROAD_STOP
The vehicle is in a drive-through road stop.
Definition roadveh.h:46
safeguards.h
A number of safeguards to prevent using unsafe methods.
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:57
_settings_client
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:56
ship.h
Base for ships.
IsShipDestinationTile
bool IsShipDestinationTile(TileIndex tile, StationID station)
Test if a tile is a docking tile for the given station.
Definition ship_cmd.cpp:647
AddTrackToSignalBuffer
void AddTrackToSignalBuffer(TileIndex tile, Track track, Owner owner)
Add track to signal update buffer.
Definition signal.cpp:592
GetSlopeMaxZ
static constexpr int GetSlopeMaxZ(Slope s)
Returns the height of the highest corner of a slope relative to TileZ (= minimal height)
Definition slope_func.h:160
IsSteepSlope
static constexpr bool IsSteepSlope(Slope s)
Checks if a slope is steep.
Definition slope_func.h:36
FlatteningFoundation
Foundation FlatteningFoundation(Slope s)
Returns the foundation needed to flatten a slope.
Definition slope_func.h:369
GetInclinedSlopeDirection
DiagDirection GetInclinedSlopeDirection(Slope s)
Returns the direction of an inclined slope.
Definition slope_func.h:239
Slope
Slope
Enumeration for the slope-type.
Definition slope_type.h:48
SLOPE_FLAT
@ SLOPE_FLAT
a flat tile
Definition slope_type.h:49
Foundation
Foundation
Enumeration for Foundations.
Definition slope_type.h:93
FOUNDATION_LEVELED
@ FOUNDATION_LEVELED
The tile is leveled up to a flat slope.
Definition slope_type.h:95
M
#define M(x)
Helper for creating a bitset of slopes.
Definition slope_type.h:84
DrawRailTileSeqInGUI
void DrawRailTileSeqInGUI(int x, int y, const DrawTileSprites *dts, int32_t total_offset, uint32_t newgrf_offset, PaletteID default_palette)
Draw tile sprite sequence in GUI with railroad specifics.
Definition sprite.h:99
DrawRailTileSeq
void DrawRailTileSeq(const struct TileInfo *ti, const DrawTileSprites *dts, TransparencyOption to, int32_t total_offset, uint32_t newgrf_offset, PaletteID default_palette)
Draw tile sprite sequence on tile with railroad specifics.
Definition sprite.h:89
GroundSpritePaletteTransform
PaletteID GroundSpritePaletteTransform(SpriteID image, PaletteID pal, PaletteID default_pal)
Applies PALETTE_MODIFIER_COLOUR to a palette entry of a ground sprite.
Definition sprite.h:168
PALETTE_CRASH
static const PaletteID PALETTE_CRASH
Recolour sprite greying of crashed vehicles.
Definition sprites.h:1605
SPRITE_MODIFIER_CUSTOM_SPRITE
static constexpr uint8_t SPRITE_MODIFIER_CUSTOM_SPRITE
these masks change the colours of the palette for a sprite.
Definition sprites.h:1545
SPRITE_WIDTH
static constexpr uint8_t SPRITE_WIDTH
number of bits for the sprite number
Definition sprites.h:1535
PALETTE_MODIFIER_COLOUR
static constexpr uint8_t PALETTE_MODIFIER_COLOUR
this bit is set when a recolouring process is in action
Definition sprites.h:1548
station_base.h
Base classes/functions for stations.
ForAllStationsAroundTiles
void ForAllStationsAroundTiles(const TileArea &ta, Func func)
Call a function on all stations that have any part of the requested area within their catchment.
Definition station_base.h:564
RemoveFromRailBaseStation
CommandCost RemoveFromRailBaseStation(TileArea ta, std::vector< T * > &affected_stations, DoCommandFlag flags, Money removal_cost, bool keep_rail)
Remove a number of tiles from any rail station within the area.
Definition station_cmd.cpp:1642
CmdOpenCloseAirport
CommandCost CmdOpenCloseAirport(DoCommandFlag flags, StationID station_id)
Open/close an airport to incoming aircraft.
Definition station_cmd.cpp:2735
ClearTile_Station
CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags)
Clear a single tile of a station.
Definition station_cmd.cpp:4696
GetEmptyMask
CargoTypes GetEmptyMask(const Station *st)
Get a mask of the cargo types that are empty at the station.
Definition station_cmd.cpp:516
BuildStationPart
static CommandCost BuildStationPart(Station **st, DoCommandFlag flags, bool reuse, TileArea area, StationNaming name_class)
Common part of building various station parts and possibly attaching them to an existing one.
Definition station_cmd.cpp:701
GetAirportNoiseLevelForDistance
uint8_t GetAirportNoiseLevelForDistance(const AirportSpec *as, uint distance)
Get a possible noise reduction factor based on distance from town center.
Definition station_cmd.cpp:2421
CmdRemoveRoadStop
CommandCost CmdRemoveRoadStop(DoCommandFlag flags, TileIndex tile, uint8_t width, uint8_t height, RoadStopType stop_type, bool remove_road)
Remove bus or truck stops.
Definition station_cmd.cpp:2381
GetAcceptanceAroundTiles
CargoArray GetAcceptanceAroundTiles(TileIndex center_tile, int w, int h, int rad, CargoTypes *always_accepted)
Get the acceptance of cargoes around the tile in 1/8.
Definition station_cmd.cpp:585
GenerateStationName
static StringID GenerateStationName(Station *st, TileIndex tile, StationNaming name_class)
Definition station_cmd.cpp:254
CanExpandRailStation
CommandCost CanExpandRailStation(const BaseStation *st, TileArea &new_ta)
Check whether we can expand the rail part of the given station.
Definition station_cmd.cpp:1081
ClearDockingTilesCheckingNeighbours
void ClearDockingTilesCheckingNeighbours(TileIndex tile)
Clear docking tile status from tiles around a removed dock, if the tile has no neighbours which would...
Definition station_cmd.cpp:2898
CMSAMatcher
bool(* CMSAMatcher)(TileIndex tile)
Function to check whether the given tile matches some criterion.
Definition station_cmd.cpp:144
IsHangar
bool IsHangar(Tile t)
Check whether the given tile is a hangar.
Definition station_cmd.cpp:92
GetClosestDeletedStation
static Station * GetClosestDeletedStation(TileIndex tile)
Find the closest deleted station of the current company.
Definition station_cmd.cpp:388
CmdRemoveFromRoadWaypoint
CommandCost CmdRemoveFromRoadWaypoint(DoCommandFlag flags, TileIndex start, TileIndex end)
Remove road waypoints.
Definition station_cmd.cpp:2403
RerouteCargo
void RerouteCargo(Station *st, CargoID c, StationID avoid, StationID avoid2)
Reroute cargo of type c at station st or in any vehicles unloading there.
Definition station_cmd.cpp:4000
CheckFlatLandRailStation
static CommandCost CheckFlatLandRailStation(TileIndex tile_cur, TileIndex north_tile, int &allowed_z, DoCommandFlag flags, Axis axis, StationID *station, RailType rt, std::vector< Train * > &affected_vehicles, StationClassID spec_class, uint16_t spec_index, uint8_t plat_len, uint8_t numtracks)
Checks if a rail station can be built at the given tile.
Definition station_cmd.cpp:886
CMSAMine
static bool CMSAMine(TileIndex tile)
Check whether the tile is a mine.
Definition station_cmd.cpp:171
CmdRemoveFromRailStation
CommandCost CmdRemoveFromRailStation(DoCommandFlag flags, TileIndex start, TileIndex end, bool keep_rail)
Remove a single tile from a rail station.
Definition station_cmd.cpp:1749
TruncateCargo
static void TruncateCargo(const CargoSpec *cs, GoodsEntry *ge, uint amount=UINT_MAX)
Truncate the cargo by a specific amount.
Definition station_cmd.cpp:3817
CheckFlatLandAirport
static CommandCost CheckFlatLandAirport(AirportTileTableIterator tile_iter, DoCommandFlag flags)
Checks if an airport can be built at the given location and clear the area.
Definition station_cmd.cpp:852
FindJoiningWaypoint
CommandCost FindJoiningWaypoint(StationID existing_waypoint, StationID waypoint_to_join, bool adjacent, TileArea ta, Waypoint **wp, bool is_road)
Find a nearby waypoint that joins this waypoint.
Definition station_cmd.cpp:1222
GetStationAround
CommandCost GetStationAround(TileArea ta, StationID closest_station, CompanyID company, T **st, F filter)
Look for a station owned by the given company around the given tile area.
Definition station_cmd.cpp:119
HasStationInUse
bool HasStationInUse(StationID station, bool include_company, CompanyID company)
Tests whether the company's vehicles have this station in orders.
Definition station_cmd.cpp:2758
CountMapSquareAround
static int CountMapSquareAround(TileIndex tile, CMSAMatcher cmp)
Counts the numbers of tiles matching a specific type in the area around.
Definition station_cmd.cpp:152
GetStationTileFlags
static StationSpec::TileFlags GetStationTileFlags(StationGfx gfx, const StationSpec *statspec)
Get station tile flags for the given StationGfx.
Definition station_cmd.cpp:1310
GetStationTileLayout
const DrawTileSprites * GetStationTileLayout(StationType st, uint8_t gfx)
Get station tile layout for a station type and its station gfx.
Definition station_cmd.cpp:3014
CmdBuildDock
CommandCost CmdBuildDock(DoCommandFlag flags, TileIndex tile, StationID station_to_join, bool adjacent)
Build a dock/haven.
Definition station_cmd.cpp:2791
GetStationLayout
void GetStationLayout(uint8_t *layout, uint numtracks, uint plat_len, const StationSpec *statspec)
Create the station layout for the given number of tracks and platform length.
Definition station_cmd.cpp:1126
FindNearIndustryName
static bool FindNearIndustryName(TileIndex tile, void *user_data)
Find a station action 0 property 24 station name, or reduce the free_names if needed.
Definition station_cmd.cpp:238
RemoveRailWaypoint
static CommandCost RemoveRailWaypoint(TileIndex tile, DoCommandFlag flags)
Remove a rail waypoint.
Definition station_cmd.cpp:1858
UpdateAllStationVirtCoords
void UpdateAllStationVirtCoords()
Update the virtual coords needed to draw the station sign for all stations.
Definition station_cmd.cpp:476
CMSAWater
static bool CMSAWater(TileIndex tile)
Check whether the tile is water.
Definition station_cmd.cpp:198
CalculateRailStationCost
static CommandCost CalculateRailStationCost(TileArea tile_area, DoCommandFlag flags, Axis axis, StationID *station, RailType rt, std::vector< Train * > &affected_vehicles, StationClassID spec_class, uint16_t spec_index, uint8_t plat_len, uint8_t numtracks)
Calculates cost of new rail stations within the area.
Definition station_cmd.cpp:1269
TriggerWatchedCargoCallbacks
void TriggerWatchedCargoCallbacks(Station *st)
Run the watched cargo callback for all houses in the catchment area.
Definition station_cmd.cpp:3758
CmdBuildAirport
CommandCost CmdBuildAirport(DoCommandFlag flags, TileIndex tile, uint8_t airport_type, uint8_t layout, StationID station_to_join, bool allow_adjacent)
Place an Airport.
Definition station_cmd.cpp:2525
CmdBuildRoadStop
CommandCost CmdBuildRoadStop(DoCommandFlag flags, TileIndex tile, uint8_t width, uint8_t length, RoadStopType stop_type, bool is_drive_through, DiagDirection ddir, RoadType rt, RoadStopClassID spec_class, uint16_t spec_index, StationID station_to_join, bool adjacent)
Build a bus or truck stop.
Definition station_cmd.cpp:1964
CheckFlatLandRoadStop
CommandCost CheckFlatLandRoadStop(TileIndex cur_tile, int &allowed_z, DoCommandFlag flags, uint invalid_dirs, bool is_drive_through, StationType station_type, Axis axis, StationID *station, RoadType rt)
Checks if a road stop can be built at the given tile.
Definition station_cmd.cpp:968
CmdRemoveFromRailWaypoint
CommandCost CmdRemoveFromRailWaypoint(DoCommandFlag flags, TileIndex start, TileIndex end, bool keep_rail)
Remove a single tile from a waypoint.
Definition station_cmd.cpp:1782
RemoveAirport
static CommandCost RemoveAirport(TileIndex tile, DoCommandFlag flags)
Remove an airport.
Definition station_cmd.cpp:2654
RemoveDock
static CommandCost RemoveDock(TileIndex tile, DoCommandFlag flags)
Remove a dock.
Definition station_cmd.cpp:2942
FindRoadStopSpot
static RoadStop ** FindRoadStopSpot(bool truck_station, Station *st)
Definition station_cmd.cpp:1874
GetAcceptanceMask
CargoTypes GetAcceptanceMask(const Station *st)
Get a mask of the cargo types that the station accepts.
Definition station_cmd.cpp:501
CheckBuildableTile
CommandCost CheckBuildableTile(TileIndex tile, uint invalid_dirs, int &allowed_z, bool allow_steep, bool check_bridge=true)
Checks if the given tile is buildable, flat and has a certain height.
Definition station_cmd.cpp:803
RestoreTrainReservation
static void RestoreTrainReservation(Train *v)
Restore platform reservation during station building/removing.
Definition station_cmd.cpp:1247
UpdateAirportsNoise
void UpdateAirportsNoise()
Recalculate the noise generated by the airports of each town.
Definition station_cmd.cpp:2502
_economy_stations_monthly
static IntervalTimer< TimerGameEconomy > _economy_stations_monthly({TimerGameEconomy::MONTH, TimerGameEconomy::Priority::STATION}, [](auto) { for(Station *st :Station::Iterate()) { for(GoodsEntry &ge :st->goods) { SB(ge.status, GoodsEntry::GES_LAST_MONTH, 1, GB(ge.status, GoodsEntry::GES_CURRENT_MONTH, 1));ClrBit(ge.status, GoodsEntry::GES_CURRENT_MONTH);} } })
Economy monthly loop for stations.
CMSATree
static bool CMSATree(TileIndex tile)
Check whether the tile is a tree.
Definition station_cmd.cpp:208
UpdateStationAcceptance
void UpdateStationAcceptance(Station *st, bool show_msg)
Update the acceptance for a station.
Definition station_cmd.cpp:625
CmdBuildRailStation
CommandCost CmdBuildRailStation(DoCommandFlag flags, TileIndex tile_org, RailType rt, Axis axis, uint8_t numtracks, uint8_t plat_len, StationClassID spec_class, uint16_t spec_index, StationID station_to_join, bool adjacent)
Build rail station.
Definition station_cmd.cpp:1344
FindJoiningRoadStop
static CommandCost FindJoiningRoadStop(StationID existing_stop, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
Find a nearby station that joins this road stop.
Definition station_cmd.cpp:1901
CmdRenameStation
CommandCost CmdRenameStation(DoCommandFlag flags, StationID station_id, const std::string &text)
Rename a station.
Definition station_cmd.cpp:4313
FindDockLandPart
static TileIndex FindDockLandPart(TileIndex t)
Find the part of a dock that is land-based.
Definition station_cmd.cpp:2919
RemoveGenericRoadStop
static CommandCost RemoveGenericRoadStop(DoCommandFlag flags, const TileArea &roadstop_area, StationType station_type, bool remove_road)
Remove a tile area of road stop or road waypoints.
Definition station_cmd.cpp:2318
FreeTrainReservation
static void FreeTrainReservation(Train *v)
Clear platform reservation during station building/removing.
Definition station_cmd.cpp:1235
SetRailStationTileFlags
void SetRailStationTileFlags(TileIndex tile, const StationSpec *statspec)
Set rail station tile flags for the given tile.
Definition station_cmd.cpp:1322
CanRemoveRoadWithStop
static CommandCost CanRemoveRoadWithStop(TileIndex tile, DoCommandFlag flags)
Check if a drive-through road stop tile can be cleared.
Definition station_cmd.cpp:4661
GetAcceptanceAroundStation
static CargoArray GetAcceptanceAroundStation(const Station *st, CargoTypes *always_accepted)
Get the acceptance of cargoes around the station in.
Definition station_cmd.cpp:607
SplitGroundSpriteForOverlay
bool SplitGroundSpriteForOverlay(const TileInfo *ti, SpriteID *ground, RailTrackOffset *overlay_offset)
Check whether a sprite is a track sprite, which can be replaced by a non-track ground sprite and a ra...
Definition station_cmd.cpp:3030
GetProductionAroundTiles
CargoArray GetProductionAroundTiles(TileIndex north_tile, int w, int h, int rad)
Get the cargo types being produced around the tile (in a rectangle).
Definition station_cmd.cpp:547
IncreaseStats
void IncreaseStats(Station *st, CargoID cargo, StationID next_station_id, uint capacity, uint usage, uint32_t time, EdgeUpdateMode mode)
Increase capacity for a link stat given by station cargo and next hop.
Definition station_cmd.cpp:4118
FindJoiningStation
static CommandCost FindJoiningStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
Find a nearby station that joins this station.
Definition station_cmd.cpp:1207
DeleteStaleLinks
void DeleteStaleLinks(Station *from)
Check all next hops of cargo packets in this station for existence of a a valid link they may use to ...
Definition station_cmd.cpp:4024
FindJoiningBaseStation
CommandCost FindJoiningBaseStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, T **st, F filter)
Find a nearby station that joins this station.
Definition station_cmd.cpp:1163
AirportGetNearestTown
Town * AirportGetNearestTown(const AirportSpec *as, Direction rotation, TileIndex tile, TileIterator &&it, uint &mindist)
Finds the town nearest to given airport.
Definition station_cmd.cpp:2452
RemoveRoadStop
static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags, int replacement_spec_index=-1)
Remove a bus station/truck stop.
Definition station_cmd.cpp:2140
CalculateRoadStopCost
CommandCost CalculateRoadStopCost(TileArea tile_area, DoCommandFlag flags, bool is_drive_through, StationType station_type, Axis axis, DiagDirection ddir, StationID *est, RoadType rt, Money unit_cost)
Calculates cost of new road stops within the area.
Definition station_cmd.cpp:1919
StationHandleBigTick
static bool StationHandleBigTick(BaseStation *st)
This function is called for each station once every 250 ticks.
Definition station_cmd.cpp:3784
RemoveRoadWaypointStop
CommandCost RemoveRoadWaypointStop(TileIndex tile, DoCommandFlag flags, int replacement_spec_index=-1)
Remove a road waypoint.
Definition station_cmd.cpp:2254
ShowRejectOrAcceptNews
static void ShowRejectOrAcceptNews(const Station *st, CargoTypes cargoes, bool reject)
Add news item for when a station changes which cargoes it accepts.
Definition station_cmd.cpp:532
RemoveRailStation
CommandCost RemoveRailStation(T *st, DoCommandFlag flags, Money removal_cost)
Remove a rail station/waypoint.
Definition station_cmd.cpp:1803
DeleteStationIfEmpty
static void DeleteStationIfEmpty(BaseStation *st)
This is called right after a station was deleted.
Definition station_cmd.cpp:738
station_cmd.h
Command definitions related to stations.
station_func.h
Functions related to stations.
ShowStationViewWindow
void ShowStationViewWindow(StationID station)
Opens StationViewWindow for given station.
Definition station_gui.cpp:2176
station_kdtree.h
Declarations for accessing the k-d tree of stations.
ForAllStationsRadius
void ForAllStationsRadius(TileIndex center, uint radius, Func func)
Call a function on all stations whose sign is within a radius of a center tile.
Definition station_kdtree.h:35
station_land.h
Sprites to use and how to display them for station tiles.
MakeAirport
void MakeAirport(Tile t, Owner o, StationID sid, uint8_t section, WaterClass wc)
Make the given tile an airport tile.
Definition station_map.h:811
GetStationType
StationType GetStationType(Tile t)
Get the station type of this tile.
Definition station_map.h:44
GetStationGfx
StationGfx GetStationGfx(Tile t)
Get the station graphics of this tile.
Definition station_map.h:68
SetStationGfx
void SetStationGfx(Tile t, StationGfx gfx)
Set the station graphics of this tile.
Definition station_map.h:80
MakeRoadStop
void MakeRoadStop(Tile t, Owner o, StationID sid, RoadStopType rst, RoadType road_rt, RoadType tram_rt, DiagDirection d)
Make the given tile a roadstop tile.
Definition station_map.h:775
SetCustomStationSpecIndex
void SetCustomStationSpecIndex(Tile t, uint8_t specindex)
Set the custom station spec for this tile.
Definition station_map.h:630
SetStationTileHaveWires
void SetStationTileHaveWires(Tile t, bool b)
Set the catenary wires state of the rail station.
Definition station_map.h:467
IsAirport
bool IsAirport(Tile t)
Is this station tile an airport?
Definition station_map.h:157
IsBayRoadStopTile
bool IsBayRoadStopTile(Tile t)
Is tile t a bay (non-drive through) road stop station?
Definition station_map.h:266
GetCustomRoadStopSpecIndex
uint GetCustomRoadStopSpecIndex(Tile t)
Get the custom road stop spec for this tile.
Definition station_map.h:678
GFX_DOCK_BASE_WATER_PART
static const int GFX_DOCK_BASE_WATER_PART
The offset for the water parts.
Definition station_map.h:35
IsBuoy
bool IsBuoy(Tile t)
Is tile t a buoy tile?
Definition station_map.h:400
IsCompatibleTrainStationTile
bool IsCompatibleTrainStationTile(Tile test_tile, Tile station_tile)
Check if a tile is a valid continuation to a railstation tile.
Definition station_map.h:544
IsRoadWaypoint
bool IsRoadWaypoint(Tile t)
Is the station at t a road waypoint?
Definition station_map.h:202
MakeDriveThroughRoadStop
void MakeDriveThroughRoadStop(Tile t, Owner station, Owner road, Owner tram, StationID sid, StationType rst, RoadType road_rt, RoadType tram_rt, Axis a)
Make the given tile a drivethrough roadstop tile.
Definition station_map.h:795
IsDriveThroughStopTile
bool IsDriveThroughStopTile(Tile t)
Is tile t a drive through road stop station or waypoint?
Definition station_map.h:276
GetRoadWaypointRoadside
static Roadside GetRoadWaypointRoadside(Tile tile)
Get the decorations of a road waypoint.
Definition station_map.h:288
IsRailStationTile
bool IsRailStationTile(Tile t)
Is this tile a station tile and a rail station?
Definition station_map.h:102
GetRailStationTrack
Track GetRailStationTrack(Tile t)
Get the rail track of a rail station tile.
Definition station_map.h:515
ToggleRoadWaypointOnSnowOrDesert
static void ToggleRoadWaypointOnSnowOrDesert(Tile t)
Toggle the snow/desert state of a road waypoint tile.
Definition station_map.h:320
GetStationIndex
StationID GetStationIndex(Tile t)
Get StationID from a tile.
Definition station_map.h:28
HasStationTileRail
bool HasStationTileRail(Tile t)
Has this station tile a rail? In other words, is this station tile a rail station or rail waypoint?
Definition station_map.h:146
GetAirportGfx
StationGfx GetAirportGfx(Tile t)
Get the station graphics of this airport tile.
Definition station_map.h:332
GetCustomStationSpecIndex
uint GetCustomStationSpecIndex(Tile t)
Get the custom station spec for this tile.
Definition station_map.h:642
IsRailWaypoint
bool IsRailWaypoint(Tile t)
Is this station tile a rail waypoint?
Definition station_map.h:113
IsRailStation
bool IsRailStation(Tile t)
Is this station tile a rail station?
Definition station_map.h:92
IsDockTile
bool IsDockTile(Tile t)
Is tile t a dock tile?
Definition station_map.h:389
SetRoadWaypointRoadside
static void SetRoadWaypointRoadside(Tile tile, Roadside s)
Set the decorations of a road waypoint.
Definition station_map.h:299
SetStationTileRandomBits
void SetStationTileRandomBits(Tile t, uint8_t random_bits)
Set the random bits for a station tile.
Definition station_map.h:690
IsAnyRoadStop
bool IsAnyRoadStop(Tile t)
Is the station at t a road station?
Definition station_map.h:245
MakeOilrig
void MakeOilrig(Tile t, StationID sid, WaterClass wc)
Make the given tile an oilrig tile.
Definition station_map.h:850
GetDockDirection
DiagDirection GetDockDirection(Tile t)
Get the direction of a dock.
Definition station_map.h:595
GetRailStationAxis
Axis GetRailStationAxis(Tile t)
Get the rail direction of a rail station.
Definition station_map.h:503
IsRoadWaypointOnSnowOrDesert
static bool IsRoadWaypointOnSnowOrDesert(Tile t)
Check if a road waypoint tile has snow/desert.
Definition station_map.h:310
IsRoadWaypointTile
bool IsRoadWaypointTile(Tile t)
Is this tile a station tile and a road waypoint?
Definition station_map.h:212
IsStationTileBlocked
bool IsStationTileBlocked(Tile t)
Is tile t a blocked tile?
Definition station_map.h:431
IsTruckStop
bool IsTruckStop(Tile t)
Is the station at t a truck stop?
Definition station_map.h:180
IsStationRoadStop
bool IsStationRoadStop(Tile t)
Is the station at t a road station?
Definition station_map.h:223
IsCustomStationSpecIndex
bool IsCustomStationSpecIndex(Tile t)
Is there a custom rail station spec on this tile?
Definition station_map.h:618
HasStationRail
bool HasStationRail(Tile t)
Has this station tile a rail? In other words, is this station tile a rail station or rail waypoint?
Definition station_map.h:135
GetDriveThroughStopAxis
Axis GetDriveThroughStopAxis(Tile t)
Gets the axis of the drive through stop.
Definition station_map.h:356
SetStationTileHavePylons
void SetStationTileHavePylons(Tile t, bool b)
Set the catenary pylon state of the rail station.
Definition station_map.h:491
IsOilRig
bool IsOilRig(Tile t)
Is tile t part of an oilrig?
Definition station_map.h:368
IsBuoyTile
bool IsBuoyTile(Tile t)
Is tile t a buoy tile?
Definition station_map.h:410
MakeRailStation
void MakeRailStation(Tile t, Owner o, StationID sid, Axis a, uint8_t section, RailType rt)
Make the given tile a rail station tile.
Definition station_map.h:742
HasStationReservation
bool HasStationReservation(Tile t)
Get the reservation state of the rail station.
Definition station_map.h:559
MakeDock
void MakeDock(Tile t, Owner o, StationID sid, DiagDirection d, WaterClass wc)
Make the given tile a dock tile.
Definition station_map.h:838
GetBayRoadStopDir
DiagDirection GetBayRoadStopDir(Tile t)
Gets the direction the bay road stop entrance points towards.
Definition station_map.h:344
IsDock
bool IsDock(Tile t)
Is tile t a dock tile?
Definition station_map.h:379
IsAnyRoadStopTile
bool IsAnyRoadStopTile(Tile t)
Is tile t a road stop station?
Definition station_map.h:256
SetStationTileBlocked
void SetStationTileBlocked(Tile t, bool b)
Set the blocked state of the rail station.
Definition station_map.h:443
GetRoadStopType
RoadStopType GetRoadStopType(Tile t)
Get the road stop type of this tile.
Definition station_map.h:56
SetCustomRoadStopSpecIndex
void SetCustomRoadStopSpecIndex(Tile t, uint8_t specindex)
Set the custom road stop spec for this tile.
Definition station_map.h:666
RoadStopType
RoadStopType
Types of RoadStops.
Definition station_type.h:45
ROADSTOP_BUS
@ ROADSTOP_BUS
A standard stop for buses.
Definition station_type.h:46
ROADSTOP_TRUCK
@ ROADSTOP_TRUCK
A standard stop for trucks.
Definition station_type.h:47
ROADSTOP_END
@ ROADSTOP_END
End of valid types.
Definition station_type.h:48
FACIL_DOCK
@ FACIL_DOCK
Station with a dock.
Definition station_type.h:58
FACIL_BUS_STOP
@ FACIL_BUS_STOP
Station with bus stops.
Definition station_type.h:56
FACIL_AIRPORT
@ FACIL_AIRPORT
Station with an airport.
Definition station_type.h:57
FACIL_WAYPOINT
@ FACIL_WAYPOINT
Station is a waypoint.
Definition station_type.h:59
FACIL_TRUCK_STOP
@ FACIL_TRUCK_STOP
Station with truck stops.
Definition station_type.h:55
FACIL_TRAIN
@ FACIL_TRAIN
Station with train station.
Definition station_type.h:54
StationType
StationType
Station types.
Definition station_type.h:31
StationList
std::set< Station *, StationCompare > StationList
List of stations.
Definition station_type.h:94
MAX_LENGTH_STATION_NAME_CHARS
static const uint MAX_LENGTH_STATION_NAME_CHARS
The maximum length of a station name in characters including '\0'.
Definition station_type.h:87
station_widget.h
Types related to the station widgets.
WID_SV_CLOSE_AIRPORT
@ WID_SV_CLOSE_AIRPORT
'Close airport' button.
Definition station_widget.h:26
WID_SV_ROADVEHS
@ WID_SV_ROADVEHS
List of scheduled road vehs button.
Definition station_widget.h:28
WID_SV_ACCEPT_RATING_LIST
@ WID_SV_ACCEPT_RATING_LIST
List of accepted cargoes / rating of cargoes.
Definition station_widget.h:22
WID_SV_SHIPS
@ WID_SV_SHIPS
List of scheduled ships button.
Definition station_widget.h:29
WID_SV_TRAINS
@ WID_SV_TRAINS
List of scheduled trains button.
Definition station_widget.h:27
stdafx.h
Definition of base types and functions in a cross-platform compatible way.
Utf8StringLength
size_t Utf8StringLength(const char *s)
Get the length of an UTF-8 encoded string in number of characters and thus not the number of bytes th...
Definition string.cpp:359
string_func.h
Functions related to low-level strings.
GetStringWithArgs
void GetStringWithArgs(StringBuilder &builder, StringID string, StringParameters &args, uint case_index, bool game_script)
Get a parsed string with most special stringcodes replaced by the string parameters.
Definition strings.cpp:257
SetDParam
void SetDParam(size_t n, uint64_t v)
Set a string parameter v at index n in the global string parameter array.
Definition strings.cpp:104
StringID
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
Definition strings_type.h:16
Aircraft
Aircraft, helicopters, rotors and their shadows belong to this class.
Definition aircraft.h:72
AirportFTAClass::AIRPLANES
@ AIRPLANES
Can planes land on this airport type?
Definition airport.h:147
AirportSpec
Defines the data structure for an airport.
Definition newgrf_airport.h:105
AirportSpec::name
StringID name
name of this airport
Definition newgrf_airport.h:115
AirportSpec::layouts
std::vector< AirportTileLayout > layouts
List of layouts composing the airport.
Definition newgrf_airport.h:107
AirportSpec::grf_prop
struct GRFFileProps grf_prop
Properties related to the grf file.
Definition newgrf_airport.h:121
AirportSpec::IsWithinMapBounds
bool IsWithinMapBounds(uint8_t table, TileIndex index) const
Check if the airport would be within the map bounds at the given tile.
Definition newgrf_airport.cpp:96
AirportSpec::size_y
uint8_t size_y
size of airport in y direction
Definition newgrf_airport.h:110
AirportSpec::size_x
uint8_t size_x
size of airport in x direction
Definition newgrf_airport.h:109
AirportSpec::Get
static const AirportSpec * Get(uint8_t type)
Retrieve airport spec for the given airport.
Definition newgrf_airport.cpp:55
AirportSpec::depots
std::span< const HangarTileTable > depots
Position of the depots on the airports.
Definition newgrf_airport.h:108
AirportSpec::IsAvailable
bool IsAvailable() const
Check whether this airport is available to build.
Definition newgrf_airport.cpp:82
AirportSpec::noise_level
uint8_t noise_level
noise that this airport generates
Definition newgrf_airport.h:111
AirportTileSpec
Defines the data structure of each individual tile of an airport.
Definition newgrf_airporttiles.h:68
AirportTileSpec::Get
static const AirportTileSpec * Get(StationGfx gfx)
Retrieve airport tile spec for the given airport tile.
Definition newgrf_airporttiles.cpp:37
AirportTileSpec::name
StringID name
Tile Subname string, land information on this tile will give you "AirportName (TileSubname)".
Definition newgrf_airporttiles.h:70
AirportTileSpec::animation
AnimationInfo animation
Information about the animation.
Definition newgrf_airporttiles.h:69
AirportTileSpec::GetByTile
static const AirportTileSpec * GetByTile(TileIndex tile)
Retrieve airport tile spec for the given airport tile.
Definition newgrf_airporttiles.cpp:50
AirportTileSpec::grf_prop
GRFFileProps grf_prop
properties related the the grf file
Definition newgrf_airporttiles.h:74
Airport::GetRotatedTileFromOffset
TileIndex GetRotatedTileFromOffset(TileIndexDiffC tidc) const
Add the tileoffset to the base tile of this airport but rotate it first.
Definition station_base.h:336
Airport::GetHangarNum
uint GetHangarNum(TileIndex tile) const
Get the hangar number of the hangar at a specific tile.
Definition station_base.h:387
Airport::rotation
Direction rotation
How this airport is rotated.
Definition station_base.h:296
Airport::type
uint8_t type
Type of this airport,.
Definition station_base.h:294
Airport::psa
PersistentStorage * psa
Persistent storage for NewGRF airports.
Definition station_base.h:298
Airport::GetNumHangars
uint GetNumHangars() const
Get the number of hangars on this airport.
Definition station_base.h:394
Airport::flags
uint64_t flags
stores which blocks on the airport are taken. was 16 bit earlier on, then 32
Definition station_base.h:293
Airport::GetHangarTile
TileIndex GetHangarTile(uint hangar_num) const
Get the first tile of the given hangar.
Definition station_base.h:358
Airport::GetSpec
const AirportSpec * GetSpec() const
Get the AirportSpec that from the airport type of this airport.
Definition station_base.h:305
Airport::layout
uint8_t layout
Airport layout number.
Definition station_base.h:295
AnimationInfo::triggers
uint16_t triggers
The triggers that trigger animation.
Definition newgrf_animation_type.h:22
AnimationInfo::status
uint8_t status
Status; 0: no looping, 1: looping, 0xFF: no animation.
Definition newgrf_animation_type.h:20
BaseStation
Base class for all station-ish types.
Definition base_station_base.h:59
BaseStation::facilities
StationFacility facilities
The facilities that this station has.
Definition base_station_base.h:70
BaseStation::string_id
StringID string_id
Default name (town area) of station.
Definition base_station_base.h:65
BaseStation::xy
TileIndex xy
Base tile of the station.
Definition base_station_base.h:60
BaseStation::speclist
std::vector< SpecMapping< StationSpec > > speclist
List of rail station specs of this station.
Definition base_station_base.h:72
BaseStation::cached_anim_triggers
uint8_t cached_anim_triggers
NOSAVE: Combined animation trigger bitmask, used to determine if trigger processing should happen.
Definition base_station_base.h:79
BaseStation::cached_name
std::string cached_name
NOSAVE: Cache of the resolved name of the station, if not using a custom name.
Definition base_station_base.h:66
BaseStation::train_station
TileArea train_station
Tile area the train 'station' part covers.
Definition base_station_base.h:84
BaseStation::cached_roadstop_anim_triggers
uint8_t cached_roadstop_anim_triggers
NOSAVE: Combined animation trigger bitmask for road stops, used to determine if trigger processing sh...
Definition base_station_base.h:80
BaseStation::owner
Owner owner
The owner of this station.
Definition base_station_base.h:69
BaseStation::UpdateVirtCoord
virtual void UpdateVirtCoord()=0
Update the coordinated of the sign (as shown in the viewport).
BaseStation::delete_ctr
uint8_t delete_ctr
Delete counter. If greater than 0 then it is decremented until it reaches 0; the waypoint is then is ...
Definition base_station_base.h:62
BaseStation::rect
StationRect rect
NOSAVE: Station spread out rectangle maintained by StationRect::xxx() functions.
Definition base_station_base.h:85
BaseStation::IsInUse
bool IsInUse() const
Check whether the base station currently is in use; in use means that it is not scheduled for deletio...
Definition base_station_base.h:177
BaseStation::town
Town * town
The town this station is associated with.
Definition base_station_base.h:68
BaseStation::GetByTile
static BaseStation * GetByTile(TileIndex tile)
Get the base station belonging to a specific tile.
Definition base_station_base.h:166
BaseStation::TileBelongsToRailStation
virtual bool TileBelongsToRailStation(TileIndex tile) const =0
Check whether a specific tile belongs to this station.
BaseStation::sign
TrackedViewportSign sign
NOSAVE: Dimensions of sign.
Definition base_station_base.h:61
BaseStation::build_date
TimerGameCalendar::Date build_date
Date of construction.
Definition base_station_base.h:75
BaseStation::name
std::string name
Custom name.
Definition base_station_base.h:64
BaseVehicle::type
VehicleType type
Type of vehicle.
Definition vehicle_type.h:51
CargoArray
Class for storing amounts of cargo.
Definition cargo_type.h:114
CargoPacket
Container for cargo from the same location and time.
Definition cargopacket.h:40
CargoSpec
Specification of a cargo type.
Definition cargotype.h:76
CargoSpec::classes
CargoClasses classes
Classes of this cargo type.
Definition cargotype.h:83
CargoSpec::Get
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
Definition cargotype.h:139
CargoSpec::Index
CargoID Index() const
Determines index of this cargospec.
Definition cargotype.h:110
Cheat::value
bool value
tells if the bool cheat is active or not
Definition cheat_type.h:18
Cheats::station_rating
Cheat station_rating
Fix station ratings at 100%.
Definition cheat_type.h:35
ClientSettings::gui
GUISettings gui
settings related to the GUI
Definition settings_type.h:610
CommandHelper
Definition command_func.h:83
CompanyInfrastructure::station
uint32_t station
Count of company owned station tiles.
Definition company_base.h:37
CompanyInfrastructure::rail
std::array< uint32_t, RAILTYPE_END > rail
Count of company owned track bits for each rail type.
Definition company_base.h:33
CompanyInfrastructure::water
uint32_t water
Count of company owned track bits for canals.
Definition company_base.h:36
Company
Definition company_base.h:133
Company::infrastructure
CompanyInfrastructure infrastructure
NOSAVE: Counts of company owned infrastructure.
Definition company_base.h:147
ConstructionSettings::build_on_slopes
bool build_on_slopes
allow building on slopes
Definition settings_type.h:383
ConstructionSettings::road_stop_on_town_road
bool road_stop_on_town_road
allow building of drive-through road stops on town owned roads
Definition settings_type.h:390
ConstructionSettings::road_stop_on_competitor_road
bool road_stop_on_competitor_road
allow building of drive-through road stops on roads owned by competitors
Definition settings_type.h:391
DifficultySettings::town_council_tolerance
uint8_t town_council_tolerance
minimum required town ratings to be allowed to demolish stuff
Definition settings_type.h:116
DrawTileSprites
Ground palette sprite of a tile, together with its sprite layout.
Definition sprite.h:58
DrawTileSprites::seq
const DrawTileSeqStruct * seq
Array of child sprites. Terminated with a terminator entry.
Definition sprite.h:60
DrawTileSprites::ground
PalSpriteID ground
Palette and sprite for the ground.
Definition sprite.h:59
EconomySettings::station_noise_level
bool station_noise_level
build new airports when the town noise level is still within accepted limits
Definition settings_type.h:532
GRFConfig
Information about GRF, used in the game and (part of it) in savegames.
Definition newgrf_config.h:154
GRFConfig::GetName
const char * GetName() const
Get the name of this grf.
Definition newgrf_config.cpp:92
GRFFilePropsBase::HasGrfFile
bool HasGrfFile() const
Test if this entity was introduced by NewGRF.
Definition newgrf_commons.h:320
GRFFilePropsBase::grfid
uint32_t grfid
grfid that introduced this entity.
Definition newgrf_commons.h:312
GRFFilePropsBase::grffile
const struct GRFFile * grffile
grf file that introduced this entity
Definition newgrf_commons.h:313
GRFFilePropsBase::spritegroup
std::array< const struct SpriteGroup *, Tcnt > spritegroup
pointers to the different sprites of the entity
Definition newgrf_commons.h:314
GUISettings::show_track_reservation
bool show_track_reservation
highlight reserved tracks.
Definition settings_type.h:193
GameCreationSettings::landscape
uint8_t landscape
the landscape we're currently in
Definition settings_type.h:368
GameSettings::economy
EconomySettings economy
settings to change the economy
Definition settings_type.h:602
GameSettings::construction
ConstructionSettings construction
construction of things in-game
Definition settings_type.h:594
GameSettings::difficulty
DifficultySettings difficulty
settings related to the difficulty
Definition settings_type.h:592
GameSettings::game_creation
GameCreationSettings game_creation
settings used during the creation of a game (map)
Definition settings_type.h:593
GameSettings::station
StationSettings station
settings related to station management
Definition settings_type.h:604
GameSettings::linkgraph
LinkGraphSettings linkgraph
settings for link graph calculations
Definition settings_type.h:603
GameSettings::order
OrderSettings order
settings related to orders
Definition settings_type.h:600
GoodsEntry
Stores station stats for a single cargo.
Definition station_base.h:166
GoodsEntry::flows
FlowStatMap flows
Planned flows through this station.
Definition station_base.h:211
GoodsEntry::max_waiting_cargo
uint max_waiting_cargo
Max cargo from this station waiting at any station.
Definition station_base.h:213
GoodsEntry::HasRating
bool HasRating() const
Does this cargo have a rating at this station?
Definition station_base.h:258
GoodsEntry::GES_ACCEPTANCE
@ GES_ACCEPTANCE
Set when the station accepts the cargo currently for final deliveries.
Definition station_base.h:173
GoodsEntry::GES_LAST_MONTH
@ GES_LAST_MONTH
Set when cargo was delivered for final delivery last month.
Definition station_base.h:195
GoodsEntry::GES_RATING
@ GES_RATING
This indicates whether a cargo has a rating at the station.
Definition station_base.h:183
GoodsEntry::GES_CURRENT_MONTH
@ GES_CURRENT_MONTH
Set when cargo was delivered for final delivery this month.
Definition station_base.h:201
GoodsEntry::GES_ACCEPTED_BIGTICK
@ GES_ACCEPTED_BIGTICK
Set when cargo was delivered for final delivery during the current STATION_ACCEPTANCE_TICKS interval.
Definition station_base.h:207
GoodsEntry::last_speed
uint8_t last_speed
Maximum speed (up to 255) of the last vehicle that tried to load this cargo.
Definition station_base.h:237
GoodsEntry::last_age
uint8_t last_age
Age in years (up to 255) of the last vehicle that tried to load this cargo.
Definition station_base.h:243
GoodsEntry::time_since_pickup
uint8_t time_since_pickup
Number of rating-intervals (up to 255) since the last vehicle tried to load this cargo.
Definition station_base.h:224
GoodsEntry::node
NodeID node
ID of node in link graph referring to this goods entry.
Definition station_base.h:214
GoodsEntry::cargo
StationCargoList cargo
The cargo packets of cargo waiting in this station.
Definition station_base.h:210
GoodsEntry::amount_fract
uint8_t amount_fract
Fractional part of the amount in the cargo list.
Definition station_base.h:245
GoodsEntry::link_graph
LinkGraphID link_graph
Link graph this station belongs to.
Definition station_base.h:215
GoodsEntry::HasVehicleEverTriedLoading
bool HasVehicleEverTriedLoading() const
Reports whether a vehicle has ever tried to load the cargo at this station.
Definition station_base.h:252
GoodsEntry::rating
uint8_t rating
Station rating for this cargo.
Definition station_base.h:226
GoodsEntry::status
uint8_t status
Status of this cargo, see GoodsEntryStatus.
Definition station_base.h:217
GoodsEntry::GetVia
StationID GetVia(StationID source) const
Get the best next hop for a cargo packet from station source.
Definition station_base.h:268
IndustrySpec
Defines the data structure for constructing industry.
Definition industrytype.h:101
IndustrySpec::name
StringID name
Displayed name of the industry.
Definition industrytype.h:121
IndustrySpec::grf_prop
GRFFileProps grf_prop
properties related to the grf file
Definition industrytype.h:132
IndustrySpec::station_name
StringID station_name
Default name for nearby station.
Definition industrytype.h:126
IndustrySpec::life_type
IndustryLifeType life_type
This is also known as Industry production flag, in newgrf specs.
Definition industrytype.h:117
IndustrySpec::enabled
bool enabled
entity still available (by default true).newgrf can disable it, though
Definition industrytype.h:131
Industry
Defines the internal data of a functional industry.
Definition industry.h:66
Industry::type
IndustryType type
type of industry.
Definition industry.h:102
Industry::produced
ProducedCargoes produced
produced cargo slots
Definition industry.h:97
Industry::owner
Owner owner
owner of the industry. Which SHOULD always be (imho) OWNER_NONE
Definition industry.h:103
Industry::GetByTile
static Industry * GetByTile(TileIndex tile)
Get the industry of the given tile.
Definition industry.h:238
Industry::location
TileArea location
Location of the industry.
Definition industry.h:94
Industry::neutral_station
Station * neutral_station
Associated neutral station.
Definition industry.h:96
Industry::stations_near
StationList stations_near
NOSAVE: List of nearby stations.
Definition industry.h:110
LinkGraph::BaseEdge
An edge in the link graph.
Definition linkgraph.h:42
Map::SizeY
static uint SizeY()
Get the size of the map along the Y.
Definition map_func.h:279
Map::SizeX
static debug_inline uint SizeX()
Get the size of the map along the X.
Definition map_func.h:270
Map::Size
static debug_inline uint Size()
Get the size of the map.
Definition map_func.h:288
NewGRFSpecBase::class_index
Tindex class_index
Class index of this spec, invalid until class is allocated.
Definition newgrf_class.h:18
NewGRFSpriteLayout
NewGRF supplied spritelayout.
Definition newgrf_commons.h:112
NewGRFSpriteLayout::PrepareLayout
uint32_t PrepareLayout(uint32_t orig_offset, uint32_t newgrf_ground_offset, uint32_t newgrf_offset, uint constr_stage, bool separate_ground) const
Prepares a sprite layout before resolving action-1-2-3 chains.
Definition newgrf_commons.cpp:645
NewGRFSpriteLayout::ProcessRegisters
void ProcessRegisters(uint8_t resolved_var10, uint32_t resolved_sprite, bool separate_ground) const
Evaluates the register modifiers and integrates them into the preprocessed sprite layout.
Definition newgrf_commons.cpp:716
NewGRFSpriteLayout::NeedsPreprocessing
bool NeedsPreprocessing() const
Tests whether this spritelayout needs preprocessing by PrepareLayout() and ProcessRegisters(),...
Definition newgrf_commons.h:149
NewGRFSpriteLayout::GetLayout
const DrawTileSeqStruct * GetLayout(PalSpriteID *ground) const
Returns the result spritelayout after preprocessing.
Definition newgrf_commons.h:162
OrderBackup::Reset
static void Reset(TileIndex tile=INVALID_TILE, bool from_gui=true)
Reset the OrderBackups from GUI/game logic.
Definition order_backup.cpp:187
OrderList
Shared order list linking together the linked list of orders and the list of vehicles sharing this or...
Definition order_base.h:259
OrderSettings::selectgoods
bool selectgoods
only send the goods to station if a train has been there
Definition settings_type.h:483
Order
Definition order_base.h:36
Order::IsType
bool IsType(OrderType type) const
Check whether this order is of the given type.
Definition order_base.h:70
Order::next
Order * next
Pointer to next order. If nullptr, end of list.
Definition order_base.h:59
Order::ShouldStopAtStation
bool ShouldStopAtStation(const Vehicle *v, StationID station) const
Check whether the given vehicle should stop at the given station based on this order and the non-stop...
Definition order_cmd.cpp:2225
OrthogonalTileArea
Represents the covered area of e.g.
Definition tilearea_type.h:18
OrthogonalTileArea::w
uint16_t w
The width of the area.
Definition tilearea_type.h:20
OrthogonalTileArea::Add
void Add(TileIndex to_add)
Add a single tile to a tile area; enlarge if needed.
Definition tilearea.cpp:43
OrthogonalTileArea::Clear
void Clear()
Clears the 'tile area', i.e.
Definition tilearea_type.h:40
OrthogonalTileArea::tile
TileIndex tile
The base tile of the area.
Definition tilearea_type.h:19
OrthogonalTileArea::h
uint16_t h
The height of the area.
Definition tilearea_type.h:21
OrthogonalTileArea::Expand
OrthogonalTileArea & Expand(int rad)
Expand a tile area by rad tiles in each direction, keeping within map bounds.
Definition tilearea.cpp:123
PalSpriteID::sprite
SpriteID sprite
The 'real' sprite.
Definition gfx_type.h:24
PalSpriteID::pal
PaletteID pal
The palette (use PAL_NONE) if not needed)
Definition gfx_type.h:25
Point
Coordinates of a point in 2D.
Definition geometry_type.hpp:21
Pool::PoolItem::index
Tindex index
Index of this pool item.
Definition pool_type.hpp:238
Pool::PoolItem<&_town_pool >::GetNumItems
static size_t GetNumItems()
Returns number of valid items in the pool.
Definition pool_type.hpp:369
Pool::PoolItem<&_link_graph_pool >::IsValidID
static bool IsValidID(size_t index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
Definition pool_type.hpp:328
Pool::PoolItem<&_station_pool >::Iterate
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
Definition pool_type.hpp:388
Pool::PoolItem<&_link_graph_pool >::GetIfValid
static Titem * GetIfValid(size_t index)
Returns Titem with given index.
Definition pool_type.hpp:350
Pool::PoolItem<&_station_pool >::CanAllocateItem
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function()
Definition pool_type.hpp:309
Pool::PoolItem<&_industry_pool >::Get
static Titem * Get(size_t index)
Returns Titem with given index.
Definition pool_type.hpp:339
RoadStopResolverObject
Road stop resolver.
Definition newgrf_roadstop.h:110
RoadStopSpec
Road stop specification.
Definition newgrf_roadstop.h:135
RoadStopSpec::GetBuildCost
Money GetBuildCost(Price category) const
Get the cost for building a road stop of this type.
Definition newgrf_roadstop.h:164
RoadStopSpec::grf_prop
GRFFilePropsBase< NUM_CARGO+3 > grf_prop
Properties related the the grf file.
Definition newgrf_roadstop.h:142
RoadStopSpec::GetClearCost
Money GetClearCost(Price category) const
Get the cost for clearing a road stop of this type.
Definition newgrf_roadstop.h:170
RoadStop
A Stop for a Road Vehicle.
Definition roadstop_base.h:22
RoadStop::next
RoadStop * next
Next stop of the given type at this station.
Definition roadstop_base.h:70
RoadStop::Enter
bool Enter(RoadVehicle *rv)
Enter the road stop.
Definition roadstop.cpp:231
RoadStop::GetByTile
static RoadStop * GetByTile(TileIndex tile, RoadStopType type)
Find a roadstop at given tile.
Definition roadstop.cpp:264
RoadStop::MakeDriveThrough
void MakeDriveThrough()
Join this road stop to another 'base' road stop if possible; fill all necessary data to become an act...
Definition roadstop.cpp:62
RoadStop::ClearDriveThrough
void ClearDriveThrough()
Prepare for removal of this stop; update other neighbouring stops if needed.
Definition roadstop.cpp:129
RoadVehicle
Buses, trucks and trams belong to this class.
Definition roadveh.h:98
RoadVehicle::state
uint8_t state
Definition roadveh.h:100
SetBitIterator
Iterable ensemble of each set bit in a value.
Definition bitmath_func.hpp:301
Ship
All ships have this type.
Definition ship.h:32
SpecializedStation< Waypoint, true >::IsExpected
static bool IsExpected(const BaseStation *st)
Helper for checking whether the given station is of this type.
Definition base_station_base.h:235
SpecializedStation< Station, false >::Iterate
static Pool::IterateWrapper< Station > Iterate(size_t from=0)
Returns an iterable ensemble of all valid stations of type T.
Definition base_station_base.h:305
SpecializedStation< Station, false >::Get
static Station * Get(size_t index)
Gets station with given index.
Definition base_station_base.h:254
SpecializedStation< Station, false >::GetIfValid
static Station * GetIfValid(size_t index)
Returns station if the index is a valid index for this station type.
Definition base_station_base.h:263
SpecializedStation< Station, false >::IsValidID
static bool IsValidID(size_t index)
Tests whether given index is a valid index for station of this type.
Definition base_station_base.h:245
SpecializedStation< Station, false >::From
static Station * From(BaseStation *st)
Converts a BaseStation to SpecializedStation with type checking.
Definition base_station_base.h:283
SpecializedVehicle::From
static T * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
Definition vehicle_base.h:1215
SpecializedVehicle::Last
T * Last()
Get the last vehicle in the chain.
Definition vehicle_base.h:1118
SpriteGroup
Definition newgrf_spritegroup.h:57
SpriteGroup::Resolve
virtual const SpriteGroup * Resolve(ResolverObject &object) const
Base sprite group resolver.
Definition newgrf_spritegroup.h:61
StationNameInformation
Information to handle station action 0 property 24 correctly.
Definition station_cmd.cpp:225
StationNameInformation::indtypes
std::bitset< NUM_INDUSTRYTYPES > indtypes
Bit set indicating when an industry type has been found.
Definition station_cmd.cpp:227
StationNameInformation::free_names
uint32_t free_names
Current bitset of free names (we can remove names).
Definition station_cmd.cpp:226
StationRect
StationRect - used to track station spread out rectangle - cheaper than scanning whole map.
Definition base_station_base.h:36
StationSettings::station_spread
uint8_t station_spread
amount a station may spread
Definition settings_type.h:569
StationSettings::serve_neutral_industries
bool serve_neutral_industries
company stations can serve industries with attached neutral stations
Definition settings_type.h:566
StationSettings::distant_join_stations
bool distant_join_stations
allow to join non-adjacent stations
Definition settings_type.h:567
StationSpec
Station specification.
Definition newgrf_station.h:115
StationSpec::callback_mask
uint8_t callback_mask
Bitmask of station callbacks that have to be called.
Definition newgrf_station.h:159
StationSpec::disallowed_lengths
uint8_t disallowed_lengths
Bitmask of platform lengths available for the station.
Definition newgrf_station.h:139
StationSpec::name
StringID name
Name of this station.
Definition newgrf_station.h:128
StationSpec::disallowed_platforms
uint8_t disallowed_platforms
Bitmask of number of platforms available for the station.
Definition newgrf_station.h:134
StationSpec::flags
uint8_t flags
Bitmask of flags, bit 0: use different sprite set; bit 1: divide cargo about by station size.
Definition newgrf_station.h:161
StationSpec::layouts
std::unordered_map< uint16_t, std::vector< uint8_t > > layouts
Custom platform layouts, keyed by platform and length combined.
Definition newgrf_station.h:174
StationSpec::TileFlags
TileFlags
Definition newgrf_station.h:163
StationSpec::TileFlags::NoWires
@ NoWires
Tile should NOT contain catenary wires.
StationSpec::TileFlags::Pylons
@ Pylons
Tile should contain catenary pylons.
StationSpec::TileFlags::Blocked
@ Blocked
Tile is blocked to vehicles.
StationSpec::tileflags
std::vector< TileFlags > tileflags
List of tile flags.
Definition newgrf_station.h:169
StationSpec::grf_prop
GRFFilePropsBase< NUM_CARGO+3 > grf_prop
Properties related the the grf file.
Definition newgrf_station.h:127
StationSpec::renderdata
std::vector< NewGRFSpriteLayout > renderdata
Number of tile layouts.
Definition newgrf_station.h:149
Station
Station data structure.
Definition station_base.h:439
Station::bus_stops
RoadStop * bus_stops
All the road stops.
Definition station_base.h:448
Station::ship_station
TileArea ship_station
Tile area the ship 'station' part covers.
Definition station_base.h:454
Station::indtype
IndustryType indtype
Industry type to get the name from.
Definition station_base.h:457
Station::docking_station
TileArea docking_station
Tile area the docking tiles cover.
Definition station_base.h:455
Station::always_accepted
CargoTypes always_accepted
Bitmask of always accepted cargo types (by houses, HQs, industry tiles when industry doesn't accept c...
Definition station_base.h:469
Station::goods
GoodsEntry goods[NUM_CARGO]
Goods at this station.
Definition station_base.h:468
Station::GetTileArea
void GetTileArea(TileArea *ta, StationType type) const override
Get the tile area for a given station type.
Definition station_cmd.cpp:411
Station::industry
Industry * industry
NOSAVE: Associated industry for neutral stations. (Rebuilt on load from Industry->st)
Definition station_base.h:472
Station::MoveSign
void MoveSign(TileIndex new_xy) override
Move the station main coordinate somewhere else.
Definition station_cmd.cpp:464
Station::bus_station
TileArea bus_station
Tile area the bus 'station' part covers.
Definition station_base.h:449
Station::catchment_tiles
BitmapTileArea catchment_tiles
NOSAVE: Set of individual tiles covered by catchment area.
Definition station_base.h:459
Station::RecomputeCatchment
void RecomputeCatchment(bool no_clear_nearby_lists=false)
Recompute tiles covered in our catchment area.
Definition station.cpp:462
Station::AfterStationTileSetChange
void AfterStationTileSetChange(bool adding, StationType type)
After adding/removing tiles to station, update some station-related stuff.
Definition station_cmd.cpp:753
Station::airport
Airport airport
Tile area the airport covers.
Definition station_base.h:453
Station::UpdateVirtCoord
void UpdateVirtCoord() override
Update the virtual coords needed to draw the station sign.
Definition station_cmd.cpp:442
Station::truck_station
TileArea truck_station
Tile area the truck 'station' part covers.
Definition station_base.h:451
Station::truck_stops
RoadStop * truck_stops
All the truck stops.
Definition station_base.h:450
Station::AddFacility
void AddFacility(StationFacility new_facility_bit, TileIndex facil_xy)
Called when new facility is built on the station.
Definition station.cpp:226
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > >
TileDesc
Tile description for the 'land area information' tool.
Definition tile_cmd.h:52
TileDesc::rail_speed
uint16_t rail_speed
Speed limit of rail (bridges and track)
Definition tile_cmd.h:65
TileDesc::station_name
StringID station_name
Type of station within the class.
Definition tile_cmd.h:59
TileDesc::str
StringID str
Description of the tile.
Definition tile_cmd.h:53
TileDesc::build_date
TimerGameCalendar::Date build_date
Date of construction of tile contents.
Definition tile_cmd.h:57
TileDesc::airport_class
StringID airport_class
Name of the airport class.
Definition tile_cmd.h:60
TileDesc::airport_name
StringID airport_name
Name of the airport.
Definition tile_cmd.h:61
TileDesc::tram_speed
uint16_t tram_speed
Speed limit of tram (bridges and track)
Definition tile_cmd.h:69
TileDesc::roadtype
StringID roadtype
Type of road on the tile.
Definition tile_cmd.h:66
TileDesc::tramtype
StringID tramtype
Type of tram on the tile.
Definition tile_cmd.h:68
TileDesc::railtype
StringID railtype
Type of rail on the tile.
Definition tile_cmd.h:64
TileDesc::road_speed
uint16_t road_speed
Speed limit of road (bridges and track)
Definition tile_cmd.h:67
TileDesc::grf
const char * grf
newGRF used for the tile contents
Definition tile_cmd.h:63
TileDesc::airport_tile_name
StringID airport_tile_name
Name of the airport tile.
Definition tile_cmd.h:62
TileDesc::owner
Owner owner[4]
Name of the owner(s)
Definition tile_cmd.h:55
TileDesc::owner_type
StringID owner_type[4]
Type of each owner.
Definition tile_cmd.h:56
TileDesc::station_class
StringID station_class
Class of station.
Definition tile_cmd.h:58
TileIndexDiffC
A pair-construct of a TileIndexDiff.
Definition map_type.h:31
TileInfo
Tile information, used while rendering the tile.
Definition tile_cmd.h:43
TileInfo::z
int z
Height.
Definition tile_cmd.h:48
TileInfo::x
int x
X position of the tile in unit coordinates.
Definition tile_cmd.h:44
TileInfo::tileh
Slope tileh
Slope of the tile.
Definition tile_cmd.h:46
TileInfo::tile
TileIndex tile
Tile index.
Definition tile_cmd.h:47
TileInfo::y
int y
Y position of the tile in unit coordinates.
Definition tile_cmd.h:45
TileLayoutSpriteGroup
Action 2 sprite layout for houses, industry tiles, objects and airport tiles.
Definition newgrf_spritegroup.h:248
TileTypeProcs
Set of callback functions for performing tile operations of a given tile type.
Definition tile_cmd.h:158
Town
Town data structure.
Definition town.h:54
Town::statues
CompanyMask statues
which companies have a statue?
Definition town.h:70
Town::xy
TileIndex xy
town center tile
Definition town.h:55
Town::noise_reached
uint16_t noise_reached
level of noise that all the airports are generating
Definition town.h:68
Town::MaxTownNoise
uint16_t MaxTownNoise() const
Calculate the max town noise.
Definition town.h:125
Town::exclusivity
CompanyID exclusivity
which company has exclusivity
Definition town.h:75
Town::exclusive_counter
uint8_t exclusive_counter
months till the exclusivity expires
Definition town.h:76
TrackedViewportSign::UpdatePosition
void UpdatePosition(int center, int top, StringID str, StringID str_small=STR_NULL)
Update the position of the viewport sign.
Definition viewport_type.h:60
TrackedViewportSign::kdtree_valid
bool kdtree_valid
Are the sign data valid for use with the _viewport_sign_kdtree?
Definition viewport_type.h:52
Train
'Train' is either a loco or a wagon.
Definition train.h:89
Train::GetVehicleTrackdir
Trackdir GetVehicleTrackdir() const override
Get the tracks of the train vehicle.
Definition train_cmd.cpp:4220
Vehicle
Vehicle data structure.
Definition vehicle_base.h:244
Vehicle::direction
Direction direction
facing
Definition vehicle_base.h:307
Vehicle::IsStoppedInDepot
bool IsStoppedInDepot() const
Check whether the vehicle is in the depot and stopped.
Definition vehicle_base.h:560
Vehicle::cargo
VehicleCargoList cargo
The cargo this vehicle is carrying.
Definition vehicle_base.h:341
Vehicle::date_of_last_service
TimerGameEconomy::Date date_of_last_service
Last economy date the vehicle had a service at a depot.
Definition vehicle_base.h:295
Vehicle::IsFrontEngine
debug_inline bool IsFrontEngine() const
Check if the vehicle is a front engine.
Definition vehicle_base.h:945
Vehicle::GetOrderStationLocation
virtual TileIndex GetOrderStationLocation(StationID station)
Determine the location for the station where the vehicle goes to next.
Definition vehicle_base.h:796
Vehicle::current_order
Order current_order
The current order (+ status, like: loading)
Definition vehicle_base.h:356
Vehicle::cargo_type
CargoID cargo_type
type of cargo this vehicle is carrying
Definition vehicle_base.h:342
Vehicle::Next
Vehicle * Next() const
Get the next vehicle of this vehicle.
Definition vehicle_base.h:632
Vehicle::refit_cap
uint16_t refit_cap
Capacity left over from before last refit.
Definition vehicle_base.h:345
Vehicle::vehstatus
uint8_t vehstatus
Status.
Definition vehicle_base.h:354
Vehicle::NextShared
Vehicle * NextShared() const
Get the next vehicle of the shared vehicle chain.
Definition vehicle_base.h:714
Vehicle::cur_speed
uint16_t cur_speed
current speed
Definition vehicle_base.h:328
Vehicle::tile
TileIndex tile
Current tile index.
Definition vehicle_base.h:264
Vehicle::dest_tile
TileIndex dest_tile
Heading for this tile.
Definition vehicle_base.h:271
Vehicle::owner
Owner owner
Which company owns the vehicle?
Definition vehicle_base.h:309
Waypoint
Representation of a waypoint.
Definition waypoint_base.h:23
Waypoint::road_waypoint_area
TileArea road_waypoint_area
Tile area the road waypoint part covers.
Definition waypoint_base.h:26
Waypoint::waypoint_flags
uint16_t waypoint_flags
Waypoint flags, see WaypointFlags.
Definition waypoint_base.h:25
Waypoint::UpdateVirtCoord
void UpdateVirtCoord() override
Update the virtual coords needed to draw the waypoint sign.
Definition waypoint_cmd.cpp:42
VehicleEnterTileStatus
VehicleEnterTileStatus
The returned bits of VehicleEnterTile.
Definition tile_cmd.h:21
VETSB_CANNOT_ENTER
@ VETSB_CANNOT_ENTER
The vehicle cannot enter the tile.
Definition tile_cmd.h:38
VETS_STATION_ID_OFFSET
@ VETS_STATION_ID_OFFSET
Shift the VehicleEnterTileStatus this many bits to the right to get the station ID when VETS_ENTERED_...
Definition tile_cmd.h:31
VETSB_ENTERED_STATION
@ VETSB_ENTERED_STATION
The vehicle entered a station.
Definition tile_cmd.h:36
VETSB_CONTINUE
@ VETSB_CONTINUE
Bit sets of the above specified bits.
Definition tile_cmd.h:35
IsTileFlat
bool IsTileFlat(TileIndex tile, int *h)
Check if a given tile is flat.
Definition tile_map.cpp:95
GetTileSlopeZ
std::tuple< Slope, int > GetTileSlopeZ(TileIndex tile)
Return the slope of a given tile inside the map.
Definition tile_map.cpp:55
GetTileMaxZ
int GetTileMaxZ(TileIndex t)
Get top height of the tile inside the map.
Definition tile_map.cpp:136
GetTileZ
int GetTileZ(TileIndex tile)
Get bottom height of the tile.
Definition tile_map.cpp:116
IsTileOwner
bool IsTileOwner(Tile tile, Owner owner)
Checks if a tile belongs to the given owner.
Definition tile_map.h:214
GetTileOwner
Owner GetTileOwner(Tile tile)
Returns the owner of a tile.
Definition tile_map.h:178
SetTileOwner
void SetTileOwner(Tile tile, Owner owner)
Sets the owner of a tile.
Definition tile_map.h:198
GetTileMaxPixelZ
int GetTileMaxPixelZ(TileIndex tile)
Get top height of the tile.
Definition tile_map.h:312
GetAnimationFrame
uint8_t GetAnimationFrame(Tile t)
Get the current animation frame.
Definition tile_map.h:250
IsValidTile
bool IsValidTile(Tile tile)
Checks if a tile is valid.
Definition tile_map.h:161
GetTropicZone
TropicZone GetTropicZone(Tile tile)
Get the tropic zone.
Definition tile_map.h:238
SetAnimationFrame
void SetAnimationFrame(Tile t, uint8_t frame)
Set a new animation frame.
Definition tile_map.h:262
IsTileType
static debug_inline bool IsTileType(Tile tile, TileType type)
Checks if a tile is a given tiletype.
Definition tile_map.h:150
GetTileSlope
Slope GetTileSlope(TileIndex tile)
Return the slope of a given tile inside the map.
Definition tile_map.h:279
TROPICZONE_DESERT
@ TROPICZONE_DESERT
Tile is desert.
Definition tile_type.h:78
TILE_HEIGHT
static const uint TILE_HEIGHT
Height of a height level in world coordinate AND in pixels in ZOOM_BASE.
Definition tile_type.h:18
TILE_SIZE
static const uint TILE_SIZE
Tile size in world coordinates.
Definition tile_type.h:15
INVALID_TILE
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition tile_type.h:95
TileIndex
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > > TileIndex
The index/ID of a Tile.
Definition tile_type.h:87
MP_TREES
@ MP_TREES
Tile got trees.
Definition tile_type.h:52
MP_ROAD
@ MP_ROAD
A tile with road (or tram tracks)
Definition tile_type.h:50
MP_STATION
@ MP_STATION
A tile of a station.
Definition tile_type.h:53
MP_HOUSE
@ MP_HOUSE
A house by a town.
Definition tile_type.h:51
MP_WATER
@ MP_WATER
Water tile.
Definition tile_type.h:54
MP_INDUSTRY
@ MP_INDUSTRY
Part of an industry.
Definition tile_type.h:56
TileArea
OrthogonalTileArea TileArea
Shorthand for the much more common orthogonal tile area.
Definition tilearea_type.h:102
timer.h
Definition of Interval and OneShot timers.
timer_game_calendar.h
Definition of the game-calendar-timer.
timer_game_economy.h
Definition of the game-economy-timer.
timer_game_tick.h
Definition of the tick-based game-timer.
town.h
Base of the town class.
GetTownRadiusGroup
HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
Returns the bit corresponding to the town zone of the specified tile.
Definition town_cmd.cpp:2474
ClosestTownFromTile
Town * ClosestTownFromTile(TileIndex tile, uint threshold)
Return the town closest (in distance or ownership) to a given tile, within a given threshold.
Definition town_cmd.cpp:3896
CalcClosestTownFromTile
Town * CalcClosestTownFromTile(TileIndex tile, uint threshold=UINT_MAX)
Return the town closest to the given tile within threshold.
Definition town_cmd.cpp:3878
CheckIfAuthorityAllowsNewStation
CommandCost CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags)
Checks whether the local authority allows construction of a new station (rail, road,...
Definition town_cmd.cpp:3854
TrackToTrackBits
TrackBits TrackToTrackBits(Track track)
Maps a Track to the corresponding TrackBits value.
Definition track_func.h:77
TrackBitsToTrackdirBits
TrackdirBits TrackBitsToTrackdirBits(TrackBits bits)
Converts TrackBits to TrackdirBits while allowing both directions.
Definition track_func.h:319
IsReversingRoadTrackdir
bool IsReversingRoadTrackdir(Trackdir dir)
Checks whether the trackdir means that we are reversing.
Definition track_func.h:673
ReverseTrackdir
Trackdir ReverseTrackdir(Trackdir trackdir)
Maps a trackdir to the reverse trackdir.
Definition track_func.h:247
CombineTrackStatus
TrackStatus CombineTrackStatus(TrackdirBits trackdirbits, TrackdirBits red_signals)
Builds a TrackStatus.
Definition track_func.h:388
AxisToTrackBits
TrackBits AxisToTrackBits(Axis a)
Maps an Axis to the corresponding TrackBits value.
Definition track_func.h:88
DiagDirToDiagTrackBits
TrackBits DiagDirToDiagTrackBits(DiagDirection diagdir)
Maps a (4-way) direction to the diagonal track bits incidating with that diagdir.
Definition track_func.h:524
AxisToTrack
Track AxisToTrack(Axis a)
Convert an Axis to the corresponding Track AXIS_X -> TRACK_X AXIS_Y -> TRACK_Y Uses the fact that the...
Definition track_func.h:66
RemoveFirstTrack
Track RemoveFirstTrack(TrackBits *tracks)
Removes first Track from TrackBits and returns it.
Definition track_func.h:131
TrackdirToExitdir
DiagDirection TrackdirToExitdir(Trackdir trackdir)
Maps a trackdir to the (4-way) direction the tile is exited when following that trackdir.
Definition track_func.h:439
TrackBits
TrackBits
Allow incrementing of Track variables.
Definition track_type.h:35
TRACK_BIT_UPPER
@ TRACK_BIT_UPPER
Upper track.
Definition track_type.h:39
TRACK_BIT_LEFT
@ TRACK_BIT_LEFT
Left track.
Definition track_type.h:41
TRACK_BIT_Y
@ TRACK_BIT_Y
Y-axis track.
Definition track_type.h:38
TRACK_BIT_NONE
@ TRACK_BIT_NONE
No track.
Definition track_type.h:36
TRACK_BIT_X
@ TRACK_BIT_X
X-axis track.
Definition track_type.h:37
TRACK_BIT_ALL
@ TRACK_BIT_ALL
All possible tracks.
Definition track_type.h:50
TRACK_BIT_RIGHT
@ TRACK_BIT_RIGHT
Right track.
Definition track_type.h:42
Trackdir
Trackdir
Enumeration for tracks and directions.
Definition track_type.h:67
TRACKDIR_BIT_NONE
@ TRACKDIR_BIT_NONE
No track build.
Definition track_type.h:99
Track
Track
These are used to specify a single track.
Definition track_type.h:19
TRACK_Y
@ TRACK_Y
Track along the y-axis (north-west to south-east)
Definition track_type.h:22
TRACK_X
@ TRACK_X
Track along the x-axis (north-east to south-west)
Definition track_type.h:21
train.h
Base for the train class.
TryPathReserve
bool TryPathReserve(Train *v, bool mark_as_stuck=false, bool first_tile_okay=false)
Try to reserve a path to a safe position.
Definition train_cmd.cpp:2866
FreeTrainTrackReservation
void FreeTrainTrackReservation(const Train *v)
Free the reserved path in front of a vehicle.
Definition train_cmd.cpp:2386
GetTrainStopLocation
int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, int *station_ahead, int *station_length)
Get the stop location of (the center) of the front vehicle of a train at a platform of a station.
Definition train_cmd.cpp:263
TO_BUILDINGS
@ TO_BUILDINGS
company buildings - depots, stations, HQ, ...
Definition transparency.h:27
TransportType
TransportType
Available types of transport.
Definition transport_type.h:19
TRANSPORT_RAIL
@ TRANSPORT_RAIL
Transport by train.
Definition transport_type.h:27
TRANSPORT_ROAD
@ TRANSPORT_ROAD
Transport by road vehicle.
Definition transport_type.h:28
TRANSPORT_WATER
@ TRANSPORT_WATER
Transport over water.
Definition transport_type.h:29
tunnelbridge_map.h
Functions that have tunnels and bridges in common.
EnsureNoVehicleOnGround
CommandCost EnsureNoVehicleOnGround(TileIndex tile)
Ensure there is no vehicle at the ground at the given position.
Definition vehicle.cpp:546
FindVehicleOnPos
void FindVehicleOnPos(TileIndex tile, void *data, VehicleFromPosProc *proc)
Find a vehicle from a specific location.
Definition vehicle.cpp:505
VS_TRAIN_SLOWING
@ VS_TRAIN_SLOWING
Train is slowing down.
Definition vehicle_base.h:37
vehicle_func.h
Functions related to vehicles.
VEH_INVALID
@ VEH_INVALID
Non-existing type of vehicle.
Definition vehicle_type.h:35
VEH_ROAD
@ VEH_ROAD
Road vehicle type.
Definition vehicle_type.h:25
VEH_AIRCRAFT
@ VEH_AIRCRAFT
Aircraft vehicle type.
Definition vehicle_type.h:27
VEH_SHIP
@ VEH_SHIP
Ship vehicle type.
Definition vehicle_type.h:26
VEH_TRAIN
@ VEH_TRAIN
Train vehicle type.
Definition vehicle_type.h:24
vehiclelist_func.h
Functions and type for generating vehicle lists.
FindVehiclesWithOrder
void FindVehiclesWithOrder(VehiclePredicate veh_pred, OrderPredicate ord_pred, VehicleFunc veh_func)
Find vehicles matching an order.
Definition vehiclelist_func.h:24
OffsetGroundSprite
void OffsetGroundSprite(int x, int y)
Called when a foundation has been drawn for the current tile.
Definition viewport.cpp:599
StartSpriteCombine
void StartSpriteCombine()
Starts a block of sprites, which are "combined" into a single bounding box.
Definition viewport.cpp:767
AddSortableSpriteToDraw
void AddSortableSpriteToDraw(SpriteID image, PaletteID pal, int x, int y, int w, int h, int dz, int z, bool transparent, int bb_offset_x, int bb_offset_y, int bb_offset_z, const SubSprite *sub)
Draw a (transparent) sprite at given coordinates with a given bounding box.
Definition viewport.cpp:671
EndSpriteCombine
void EndSpriteCombine()
Terminates a block of sprites started by StartSpriteCombine.
Definition viewport.cpp:777
DrawGroundSprite
void DrawGroundSprite(SpriteID image, PaletteID pal, const SubSprite *sub, int extra_offs_x, int extra_offs_y)
Draws a ground sprite for the current tile.
Definition viewport.cpp:587
viewport_func.h
Functions related to (drawing on) viewports.
water.h
Functions related to water (management)
TileLoop_Water
void TileLoop_Water(TileIndex tile)
Let a water tile floods its diagonal adjoining tiles called from tunnelbridge_cmd,...
Definition water_cmd.cpp:1245
CheckForDockingTile
void CheckForDockingTile(TileIndex t)
Mark the supplied tile as a docking tile if it is suitable for docking.
Definition water_cmd.cpp:195
HasTileWaterGround
bool HasTileWaterGround(Tile t)
Checks whether the tile has water at the ground.
Definition water_map.h:350
IsTileOnWater
bool IsTileOnWater(Tile t)
Tests if the tile was built on water.
Definition water_map.h:136
WaterClass
WaterClass
classes of water (for WATER_TILE_CLEAR water tile type).
Definition water_map.h:39
WATER_CLASS_SEA
@ WATER_CLASS_SEA
Sea.
Definition water_map.h:40
WATER_CLASS_CANAL
@ WATER_CLASS_CANAL
Canal.
Definition water_map.h:41
WATER_CLASS_INVALID
@ WATER_CLASS_INVALID
Used for industry tiles on land (also for oilrig if newgrf says so).
Definition water_map.h:43
HasTileWaterClass
bool HasTileWaterClass(Tile t)
Checks whether the tile has an waterclass associated.
Definition water_map.h:101
GetWaterClass
WaterClass GetWaterClass(Tile t)
Get the water class at a tile.
Definition water_map.h:112
IsDockingTile
bool IsDockingTile(Tile t)
Checks whether the tile is marked as a dockling tile.
Definition water_map.h:371
SetDockingTile
void SetDockingTile(Tile t, bool b)
Set the docking tile state of a tile.
Definition water_map.h:361
IsWater
bool IsWater(Tile t)
Is it a plain water tile?
Definition water_map.h:147
IsWaterTile
bool IsWaterTile(Tile t)
Is it a water tile with plain water?
Definition water_map.h:190
waypoint_base.h
Base of waypoints.
WPF_ROAD
@ WPF_ROAD
This is a road waypoint.
Definition waypoint_base.h:19
RemoveBuoy
CommandCost RemoveBuoy(TileIndex tile, DoCommandFlag flags)
Remove a buoy.
Definition waypoint_cmd.cpp:524
waypoint_cmd.h
Command definitions related to waypoints.
waypoint_func.h
Functions related to waypoints.
ShowWaypointWindow
void ShowWaypointWindow(const Waypoint *wp)
Show the window for the given waypoint.
Definition waypoint_gui.cpp:223
CloseWindowById
void CloseWindowById(WindowClass cls, WindowNumber number, bool force, int data)
Close a window by its class and window number (if it is open).
Definition window.cpp:1140
SetWindowClassesDirty
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
Definition window.cpp:3127
InvalidateWindowData
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
Definition window.cpp:3219
SetWindowWidgetDirty
void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, WidgetID widget_index)
Mark a particular widget in a particular window as dirty (in need of repainting)
Definition window.cpp:3114
SetWindowDirty
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition window.cpp:3101
InvalidateWindowClassesData
void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
Mark window data of all windows of a given class as invalid (in need of re-computing) Note that by de...
Definition window.cpp:3236
WC_STATION_LIST
@ WC_STATION_LIST
Station list; Window numbers:
Definition window_type.h:302
WC_VEHICLE_ORDERS
@ WC_VEHICLE_ORDERS
Vehicle orders; Window numbers:
Definition window_type.h:212
WC_VEHICLE_DEPOT
@ WC_VEHICLE_DEPOT
Depot view; Window numbers:
Definition window_type.h:351
WC_SELECT_STATION
@ WC_SELECT_STATION
Select station (when joining stations); Window numbers:
Definition window_type.h:242
WC_STATION_VIEW
@ WC_STATION_VIEW
Station view; Window numbers:
Definition window_type.h:345
WC_TOWN_VIEW
@ WC_TOWN_VIEW
Town view; Window numbers:
Definition window_type.h:333
yapf_cache.h
Entry point for OpenTTD to YAPF's cache.
YapfNotifyTrackLayoutChange
void YapfNotifyTrackLayoutChange(TileIndex tile, Track track)
Use this function to notify YAPF that track layout (or signal configuration) has change.
Definition yapf_rail.cpp:639