OpenTTD Source  20240917-master-g9ab0a47812
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 */
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"
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"
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"
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 
118 template <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_cmd_error(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 
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 
215 enum StationNaming {
216  STATIONNAMING_RAIL,
217  STATIONNAMING_ROAD,
218  STATIONNAMING_AIRPORT,
219  STATIONNAMING_OILRIG,
220  STATIONNAMING_DOCK,
221  STATIONNAMING_HELIPORT,
222 };
223 
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 */
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 
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 ||
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 
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 
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 
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 
458 }
459 
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 
477 {
478  for (BaseStation *st : BaseStation::Iterate()) {
479  st->UpdateVirtCoord();
480  }
481 }
482 
483 void 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 
489 void ClearAllStationCachedNames()
490 {
491  for (BaseStation *st : BaseStation::Iterate()) {
492  st->cached_name.clear();
493  }
494 }
495 
501 CargoTypes 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 
516 CargoTypes 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;
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 
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);
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 */
671 }
672 
673 static 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) {
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_cmd_error(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 
725  SetBit((*st)->town->have_ratings, _current_company);
726  }
727  }
728  }
729  return CommandCost();
730 }
731 
739 {
740  if (!st->IsInUse()) {
741  st->delete_ctr = 0;
743  }
744  /* station remains but it probably lost some parts - station sign should stay in the station boundaries */
745  UpdateStationSignCoord(st);
746 }
747 
754 {
755  this->UpdateVirtCoord();
757 
758  if (adding) {
759  this->RecomputeCatchment();
760  MarkCatchmentTilesDirty();
762  } else {
763  MarkCatchmentTilesDirty();
764  }
765 
766  switch (type) {
767  case STATION_RAIL:
769  break;
770  case STATION_AIRPORT:
771  break;
772  case STATION_TRUCK:
773  case STATION_BUS:
775  break;
776  case STATION_DOCK:
778  break;
779  default: NOT_REACHED();
780  }
781 
782  if (adding) {
783  UpdateStationAcceptance(this, false);
785  } else {
786  DeleteStationIfEmpty(this);
787  this->RecomputeCatchment();
788  }
789 
790 }
791 
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_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
807  }
808 
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)) ||
820  return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
821  }
822 
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_cmd_error(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_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
841  }
842 
843  return cost;
844 }
845 
853 {
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 {
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_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
916  }
917  }
918  } else {
919  /* Rail type is only valid when building a railway station; if station to
920  * build isn't a rail station it's INVALID_RAILTYPE. */
921  if (rt != INVALID_RAILTYPE &&
922  IsPlainRailTile(tile_cur) && !HasSignals(tile_cur) &&
923  HasPowerOnRail(GetRailType(tile_cur), rt)) {
924  /* Allow overbuilding if the tile:
925  * - has rail, but no signals
926  * - it has exactly one track
927  * - the track is in line with the station
928  * - the current rail type has power on the to-be-built type (e.g. convert normal rail to el rail)
929  */
930  TrackBits tracks = GetTrackBits(tile_cur);
931  Track track = RemoveFirstTrack(&tracks);
932  Track expected_track = HasBit(invalid_dirs, DIAGDIR_NE) ? TRACK_X : TRACK_Y;
933 
934  if (tracks == TRACK_BIT_NONE && track == expected_track) {
935  /* Check for trains having a reservation for this tile. */
936  if (HasBit(GetRailReservationTrackBits(tile_cur), track)) {
937  Train *v = GetTrainForReservation(tile_cur, track);
938  if (v != nullptr) {
939  affected_vehicles.push_back(v);
940  }
941  }
942  ret = Command<CMD_REMOVE_SINGLE_RAIL>::Do(flags, tile_cur, track);
943  if (ret.Failed()) return ret;
944  cost.AddCost(ret);
945  /* With flags & ~DC_EXEC CmdLandscapeClear would fail since the rail still exists */
946  return cost;
947  }
948  }
949  ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile_cur);
950  if (ret.Failed()) return ret;
951  cost.AddCost(ret);
952  }
953 
954  return cost;
955 }
956 
970 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)
971 {
973 
974  CommandCost ret = CheckBuildableTile(cur_tile, invalid_dirs, allowed_z, !is_drive_through);
975  if (ret.Failed()) return ret;
976  cost.AddCost(ret);
977 
978  /* If station is set, then we have special handling to allow building on top of already existing stations.
979  * Station points to INVALID_STATION if we can build on any station.
980  * Or it points to a station if we're only allowed to build on exactly that station. */
981  if (station != nullptr && IsTileType(cur_tile, MP_STATION)) {
982  if (!IsAnyRoadStop(cur_tile)) {
983  return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
984  } else {
985  if (station_type != GetStationType(cur_tile) ||
986  is_drive_through != IsDriveThroughStopTile(cur_tile)) {
987  return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
988  }
989  /* Drive-through station in the wrong direction. */
990  if (is_drive_through && IsDriveThroughStopTile(cur_tile) && DiagDirToAxis(GetRoadStopDir(cur_tile)) != axis) {
991  return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
992  }
993  StationID st = GetStationIndex(cur_tile);
994  if (*station == INVALID_STATION) {
995  *station = st;
996  } else if (*station != st) {
997  return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
998  }
999  }
1000  } else {
1001  bool build_over_road = is_drive_through && IsNormalRoadTile(cur_tile);
1002  /* Road bits in the wrong direction. */
1003  RoadBits rb = IsNormalRoadTile(cur_tile) ? GetAllRoadBits(cur_tile) : ROAD_NONE;
1004  if (build_over_road && (rb & (axis == AXIS_X ? ROAD_Y : ROAD_X)) != 0) {
1005  /* Someone was pedantic and *NEEDED* three fracking different error messages. */
1006  switch (CountBits(rb)) {
1007  case 1:
1008  return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
1009 
1010  case 2:
1011  if (rb == ROAD_X || rb == ROAD_Y) return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
1012  return_cmd_error(STR_ERROR_DRIVE_THROUGH_CORNER);
1013 
1014  default: // 3 or 4
1015  return_cmd_error(STR_ERROR_DRIVE_THROUGH_JUNCTION);
1016  }
1017  }
1018 
1019  if (build_over_road) {
1020  /* There is a road, check if we can build road+tram stop over it. */
1021  RoadType road_rt = GetRoadType(cur_tile, RTT_ROAD);
1022  if (road_rt != INVALID_ROADTYPE) {
1023  Owner road_owner = GetRoadOwner(cur_tile, RTT_ROAD);
1024  if (road_owner == OWNER_TOWN) {
1025  if (!_settings_game.construction.road_stop_on_town_road) return_cmd_error(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD);
1026  } else if (!_settings_game.construction.road_stop_on_competitor_road && road_owner != OWNER_NONE) {
1027  ret = CheckOwnership(road_owner);
1028  if (ret.Failed()) return ret;
1029  }
1030  uint num_pieces = CountBits(GetRoadBits(cur_tile, RTT_ROAD));
1031 
1032  if (rt != INVALID_ROADTYPE && RoadTypeIsRoad(rt) && !HasPowerOnRoad(rt, road_rt)) return_cmd_error(STR_ERROR_NO_SUITABLE_ROAD);
1033 
1034  if (GetDisallowedRoadDirections(cur_tile) != DRD_NONE && road_owner != OWNER_TOWN) {
1035  ret = CheckOwnership(road_owner);
1036  if (ret.Failed()) return ret;
1037  }
1038 
1039  cost.AddCost(RoadBuildCost(road_rt) * (2 - num_pieces));
1040  } else if (rt != INVALID_ROADTYPE && RoadTypeIsRoad(rt)) {
1041  cost.AddCost(RoadBuildCost(rt) * 2);
1042  }
1043 
1044  /* There is a tram, check if we can build road+tram stop over it. */
1045  RoadType tram_rt = GetRoadType(cur_tile, RTT_TRAM);
1046  if (tram_rt != INVALID_ROADTYPE) {
1047  Owner tram_owner = GetRoadOwner(cur_tile, RTT_TRAM);
1048  if (Company::IsValidID(tram_owner) &&
1050  /* Disallow breaking end-of-line of someone else
1051  * so trams can still reverse on this tile. */
1052  HasExactlyOneBit(GetRoadBits(cur_tile, RTT_TRAM)))) {
1053  ret = CheckOwnership(tram_owner);
1054  if (ret.Failed()) return ret;
1055  }
1056  uint num_pieces = CountBits(GetRoadBits(cur_tile, RTT_TRAM));
1057 
1058  if (rt != INVALID_ROADTYPE && RoadTypeIsTram(rt) && !HasPowerOnRoad(rt, tram_rt)) return_cmd_error(STR_ERROR_NO_SUITABLE_ROAD);
1059 
1060  cost.AddCost(RoadBuildCost(tram_rt) * (2 - num_pieces));
1061  } else if (rt != INVALID_ROADTYPE && RoadTypeIsTram(rt)) {
1062  cost.AddCost(RoadBuildCost(rt) * 2);
1063  }
1064  } else if (rt == INVALID_ROADTYPE) {
1065  return_cmd_error(STR_ERROR_THERE_IS_NO_ROAD);
1066  } else {
1067  ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, cur_tile);
1068  if (ret.Failed()) return ret;
1069  cost.AddCost(ret);
1070  cost.AddCost(RoadBuildCost(rt) * 2);
1071  }
1072  }
1073 
1074  return cost;
1075 }
1076 
1084 {
1085  TileArea cur_ta = st->train_station;
1086 
1087  /* determine new size of train station region.. */
1088  int x = std::min(TileX(cur_ta.tile), TileX(new_ta.tile));
1089  int y = std::min(TileY(cur_ta.tile), TileY(new_ta.tile));
1090  new_ta.w = std::max(TileX(cur_ta.tile) + cur_ta.w, TileX(new_ta.tile) + new_ta.w) - x;
1091  new_ta.h = std::max(TileY(cur_ta.tile) + cur_ta.h, TileY(new_ta.tile) + new_ta.h) - y;
1092  new_ta.tile = TileXY(x, y);
1093 
1094  /* make sure the final size is not too big. */
1096  return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
1097  }
1098 
1099  return CommandCost();
1100 }
1101 
1102 static inline uint8_t *CreateSingle(uint8_t *layout, int n)
1103 {
1104  int i = n;
1105  do *layout++ = 0; while (--i);
1106  layout[((n - 1) >> 1) - n] = 2;
1107  return layout;
1108 }
1109 
1110 static inline uint8_t *CreateMulti(uint8_t *layout, int n, uint8_t b)
1111 {
1112  int i = n;
1113  do *layout++ = b; while (--i);
1114  if (n > 4) {
1115  layout[0 - n] = 0;
1116  layout[n - 1 - n] = 0;
1117  }
1118  return layout;
1119 }
1120 
1128 void GetStationLayout(uint8_t *layout, uint numtracks, uint plat_len, const StationSpec *statspec)
1129 {
1130  if (statspec != nullptr) {
1131  auto found = statspec->layouts.find(GetStationLayoutKey(numtracks, plat_len));
1132  if (found != std::end(statspec->layouts)) {
1133  /* Custom layout defined, copy to buffer. */
1134  std::copy(std::begin(found->second), std::end(found->second), layout);
1135  return;
1136  }
1137  }
1138 
1139  if (plat_len == 1) {
1140  CreateSingle(layout, numtracks);
1141  } else {
1142  if (numtracks & 1) layout = CreateSingle(layout, plat_len);
1143  int n = numtracks >> 1;
1144 
1145  while (--n >= 0) {
1146  layout = CreateMulti(layout, plat_len, 4);
1147  layout = CreateMulti(layout, plat_len, 6);
1148  }
1149  }
1150 }
1151 
1164 template <class T, StringID error_message, class F>
1165 CommandCost FindJoiningBaseStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, T **st, F filter)
1166 {
1167  assert(*st == nullptr);
1168  bool check_surrounding = true;
1169 
1171  if (existing_station != INVALID_STATION) {
1172  if (adjacent && existing_station != station_to_join) {
1173  /* You can't build an adjacent station over the top of one that
1174  * already exists. */
1175  return_cmd_error(error_message);
1176  } else {
1177  /* Extend the current station, and don't check whether it will
1178  * be near any other stations. */
1179  T *candidate = T::GetIfValid(existing_station);
1180  if (candidate != nullptr && filter(candidate)) *st = candidate;
1181  check_surrounding = (*st == nullptr);
1182  }
1183  } else {
1184  /* There's no station here. Don't check the tiles surrounding this
1185  * one if the company wanted to build an adjacent station. */
1186  if (adjacent) check_surrounding = false;
1187  }
1188  }
1189 
1190  if (check_surrounding) {
1191  /* Make sure there is no more than one other station around us that is owned by us. */
1192  CommandCost ret = GetStationAround(ta, existing_station, _current_company, st, filter);
1193  if (ret.Failed()) return ret;
1194  }
1195 
1196  /* Distant join */
1197  if (*st == nullptr && station_to_join != INVALID_STATION) *st = T::GetIfValid(station_to_join);
1198 
1199  return CommandCost();
1200 }
1201 
1211 static CommandCost FindJoiningStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
1212 {
1213  return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_RAILWAY_STATION_FIRST>(existing_station, station_to_join, adjacent, ta, st, [](const Station *) -> bool { return true; });
1214 }
1215 
1226 CommandCost FindJoiningWaypoint(StationID existing_waypoint, StationID waypoint_to_join, bool adjacent, TileArea ta, Waypoint **wp, bool is_road)
1227 {
1228  if (is_road) {
1229  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); });
1230  } else {
1231  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); });
1232  }
1233 }
1234 
1240 {
1243  v = v->Last();
1245 }
1246 
1252 {
1254  TryPathReserve(v, true, true);
1255  v = v->Last();
1257 }
1258 
1273 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)
1274 {
1276  bool length_price_ready = true;
1277  uint8_t tracknum = 0;
1278  int allowed_z = -1;
1279  for (TileIndex cur_tile : tile_area) {
1280  /* Clear the land below the station. */
1281  CommandCost ret = CheckFlatLandRailStation(cur_tile, tile_area.tile, allowed_z, flags, axis, station, rt, affected_vehicles, spec_class, spec_index, plat_len, numtracks);
1282  if (ret.Failed()) return ret;
1283 
1284  /* Only add _price[PR_BUILD_STATION_RAIL_LENGTH] once for each valid plat_len. */
1285  if (tracknum == numtracks) {
1286  length_price_ready = true;
1287  tracknum = 0;
1288  } else {
1289  tracknum++;
1290  }
1291 
1292  /* AddCost for new or rotated rail stations. */
1293  if (!IsRailStationTile(cur_tile) || (IsRailStationTile(cur_tile) && GetRailStationAxis(cur_tile) != axis)) {
1294  cost.AddCost(ret);
1295  cost.AddCost(_price[PR_BUILD_STATION_RAIL]);
1296  cost.AddCost(RailBuildCost(rt));
1297 
1298  if (length_price_ready) {
1299  cost.AddCost(_price[PR_BUILD_STATION_RAIL_LENGTH]);
1300  length_price_ready = false;
1301  }
1302  }
1303  }
1304 
1305  return cost;
1306 }
1307 
1315 {
1316  /* Default stations do not draw pylons under roofs (gfx >= 4) */
1317  if (statspec == nullptr || gfx >= statspec->tileflags.size()) return gfx < 4 ? StationSpec::TileFlags::Pylons : StationSpec::TileFlags::None;
1318  return statspec->tileflags[gfx];
1319 }
1320 
1326 void SetRailStationTileFlags(TileIndex tile, const StationSpec *statspec)
1327 {
1328  const auto flags = GetStationTileFlags(GetStationGfx(tile), statspec);
1332 }
1333 
1348 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)
1349 {
1350  /* Does the authority allow this? */
1351  CommandCost ret = CheckIfAuthorityAllowsNewStation(tile_org, flags);
1352  if (ret.Failed()) return ret;
1353 
1354  if (!ValParamRailType(rt) || !IsValidAxis(axis)) return CMD_ERROR;
1355 
1356  /* Check if the given station class is valid */
1357  if (static_cast<uint>(spec_class) >= StationClass::GetClassCount()) return CMD_ERROR;
1358  const StationClass *cls = StationClass::Get(spec_class);
1359  if (IsWaypointClass(*cls)) return CMD_ERROR;
1360  if (spec_index >= cls->GetSpecCount()) return CMD_ERROR;
1361  if (plat_len == 0 || numtracks == 0) return CMD_ERROR;
1362 
1363  int w_org, h_org;
1364  if (axis == AXIS_X) {
1365  w_org = plat_len;
1366  h_org = numtracks;
1367  } else {
1368  h_org = plat_len;
1369  w_org = numtracks;
1370  }
1371 
1372  bool reuse = (station_to_join != NEW_STATION);
1373  if (!reuse) station_to_join = INVALID_STATION;
1374  bool distant_join = (station_to_join != INVALID_STATION);
1375 
1376  if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
1377 
1379 
1380  /* these values are those that will be stored in train_tile and station_platforms */
1381  TileArea new_location(tile_org, w_org, h_org);
1382 
1383  /* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
1384  StationID est = INVALID_STATION;
1385  std::vector<Train *> affected_vehicles;
1386  /* Add construction and clearing expenses. */
1387  CommandCost cost = CalculateRailStationCost(new_location, flags, axis, &est, rt, affected_vehicles, spec_class, spec_index, plat_len, numtracks);
1388  if (cost.Failed()) return cost;
1389 
1390  Station *st = nullptr;
1391  ret = FindJoiningStation(est, station_to_join, adjacent, new_location, &st);
1392  if (ret.Failed()) return ret;
1393 
1394  ret = BuildStationPart(&st, flags, reuse, new_location, STATIONNAMING_RAIL);
1395  if (ret.Failed()) return ret;
1396 
1397  if (st != nullptr && st->train_station.tile != INVALID_TILE) {
1398  ret = CanExpandRailStation(st, new_location);
1399  if (ret.Failed()) return ret;
1400  }
1401 
1402  /* Check if we can allocate a custom stationspec to this station */
1403  const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
1404  int specindex = AllocateSpecToStation(statspec, st, (flags & DC_EXEC) != 0);
1405  if (specindex == -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS);
1406 
1407  if (statspec != nullptr) {
1408  /* Perform NewStation checks */
1409 
1410  /* Check if the station size is permitted */
1411  if (HasBit(statspec->disallowed_platforms, std::min(numtracks - 1, 7))) return_cmd_error(STR_ERROR_STATION_DISALLOWED_NUMBER_TRACKS);
1412  if (HasBit(statspec->disallowed_lengths, std::min(plat_len - 1, 7))) return_cmd_error(STR_ERROR_STATION_DISALLOWED_LENGTH);
1413 
1414  /* Check if the station is buildable */
1415  if (HasBit(statspec->callback_mask, CBM_STATION_AVAIL)) {
1416  uint16_t cb_res = GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, nullptr, INVALID_TILE);
1417  if (cb_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(statspec->grf_prop.grffile, CBID_STATION_AVAILABILITY, cb_res)) return CMD_ERROR;
1418  }
1419  }
1420 
1421  if (flags & DC_EXEC) {
1422  TileIndexDiff tile_delta;
1423  uint8_t numtracks_orig;
1424  Track track;
1425 
1426  st->train_station = new_location;
1427  st->AddFacility(FACIL_TRAIN, new_location.tile);
1428 
1429  st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TRY);
1430 
1431  if (statspec != nullptr) {
1432  /* Include this station spec's animation trigger bitmask
1433  * in the station's cached copy. */
1434  st->cached_anim_triggers |= statspec->animation.triggers;
1435  }
1436 
1437  tile_delta = (axis == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
1438  track = AxisToTrack(axis);
1439 
1440  std::vector<uint8_t> layouts(numtracks * plat_len);
1441  GetStationLayout(layouts.data(), numtracks, plat_len, statspec);
1442 
1443  numtracks_orig = numtracks;
1444 
1445  Company *c = Company::Get(st->owner);
1446  size_t layout_idx = 0;
1447  TileIndex tile_track = tile_org;
1448  do {
1449  TileIndex tile = tile_track;
1450  int w = plat_len;
1451  do {
1452  uint8_t layout = layouts[layout_idx++];
1453  if (IsRailStationTile(tile) && HasStationReservation(tile)) {
1454  /* Check for trains having a reservation for this tile. */
1456  if (v != nullptr) {
1457  affected_vehicles.push_back(v);
1459  }
1460  }
1461 
1462  /* Railtype can change when overbuilding. */
1463  if (IsRailStationTile(tile)) {
1464  if (!IsStationTileBlocked(tile)) c->infrastructure.rail[GetRailType(tile)]--;
1465  c->infrastructure.station--;
1466  }
1467 
1468  /* Remove animation if overbuilding */
1469  DeleteAnimatedTile(tile);
1470  uint8_t old_specindex = HasStationTileRail(tile) ? GetCustomStationSpecIndex(tile) : 0;
1471  MakeRailStation(tile, st->owner, st->index, axis, layout & ~1, rt);
1472  /* Free the spec if we overbuild something */
1473  DeallocateSpecFromStation(st, old_specindex);
1474 
1475  SetCustomStationSpecIndex(tile, specindex);
1476  SetStationTileRandomBits(tile, GB(Random(), 0, 4));
1477  SetAnimationFrame(tile, 0);
1478 
1479  if (statspec != nullptr) {
1480  /* Use a fixed axis for GetPlatformInfo as our platforms / numtracks are always the right way around */
1481  uint32_t platinfo = GetPlatformInfo(AXIS_X, GetStationGfx(tile), plat_len, numtracks_orig, plat_len - w, numtracks_orig - numtracks, false);
1482 
1483  /* As the station is not yet completely finished, the station does not yet exist. */
1484  uint16_t callback = GetStationCallback(CBID_STATION_BUILD_TILE_LAYOUT, platinfo, 0, statspec, nullptr, tile);
1485  if (callback != CALLBACK_FAILED) {
1486  if (callback <= UINT8_MAX) {
1487  SetStationGfx(tile, (callback & ~1) + axis);
1488  } else {
1490  }
1491  }
1492 
1493  /* Trigger station animation -- after building? */
1494  TriggerStationAnimation(st, tile, SAT_BUILT);
1495  }
1496 
1497  SetRailStationTileFlags(tile, statspec);
1498 
1499  if (!IsStationTileBlocked(tile)) c->infrastructure.rail[rt]++;
1500  c->infrastructure.station++;
1501 
1502  tile += tile_delta;
1503  } while (--w);
1504  AddTrackToSignalBuffer(tile_track, track, _current_company);
1505  YapfNotifyTrackLayoutChange(tile_track, track);
1506  tile_track += tile_delta ^ TileDiffXY(1, 1); // perpendicular to tile_delta
1507  } while (--numtracks);
1508 
1509  for (uint i = 0; i < affected_vehicles.size(); ++i) {
1510  /* Restore reservations of trains. */
1511  RestoreTrainReservation(affected_vehicles[i]);
1512  }
1513 
1514  /* Check whether we need to expand the reservation of trains already on the station. */
1515  TileArea update_reservation_area;
1516  if (axis == AXIS_X) {
1517  update_reservation_area = TileArea(tile_org, 1, numtracks_orig);
1518  } else {
1519  update_reservation_area = TileArea(tile_org, numtracks_orig, 1);
1520  }
1521 
1522  for (TileIndex tile : update_reservation_area) {
1523  /* Don't even try to make eye candy parts reserved. */
1524  if (IsStationTileBlocked(tile)) continue;
1525 
1526  DiagDirection dir = AxisToDiagDir(axis);
1527  TileIndexDiff tile_offset = TileOffsByDiagDir(dir);
1528  TileIndex platform_begin = tile;
1529  TileIndex platform_end = tile;
1530 
1531  /* We can only account for tiles that are reachable from this tile, so ignore primarily blocked tiles while finding the platform begin and end. */
1532  for (TileIndex next_tile = platform_begin - tile_offset; IsCompatibleTrainStationTile(next_tile, platform_begin); next_tile -= tile_offset) {
1533  platform_begin = next_tile;
1534  }
1535  for (TileIndex next_tile = platform_end + tile_offset; IsCompatibleTrainStationTile(next_tile, platform_end); next_tile += tile_offset) {
1536  platform_end = next_tile;
1537  }
1538 
1539  /* If there is at least on reservation on the platform, we reserve the whole platform. */
1540  bool reservation = false;
1541  for (TileIndex t = platform_begin; !reservation && t <= platform_end; t += tile_offset) {
1542  reservation = HasStationReservation(t);
1543  }
1544 
1545  if (reservation) {
1546  SetRailStationPlatformReservation(platform_begin, dir, true);
1547  }
1548  }
1549 
1550  st->MarkTilesDirty(false);
1551  st->AfterStationTileSetChange(true, STATION_RAIL);
1552  }
1553 
1554  return cost;
1555 }
1556 
1557 static TileArea MakeStationAreaSmaller(BaseStation *st, TileArea ta, bool (*func)(BaseStation *, TileIndex))
1558 {
1559 restart:
1560 
1561  /* too small? */
1562  if (ta.w != 0 && ta.h != 0) {
1563  /* check the left side, x = constant, y changes */
1564  for (uint i = 0; !func(st, ta.tile + TileDiffXY(0, i));) {
1565  /* the left side is unused? */
1566  if (++i == ta.h) {
1567  ta.tile += TileDiffXY(1, 0);
1568  ta.w--;
1569  goto restart;
1570  }
1571  }
1572 
1573  /* check the right side, x = constant, y changes */
1574  for (uint i = 0; !func(st, ta.tile + TileDiffXY(ta.w - 1, i));) {
1575  /* the right side is unused? */
1576  if (++i == ta.h) {
1577  ta.w--;
1578  goto restart;
1579  }
1580  }
1581 
1582  /* check the upper side, y = constant, x changes */
1583  for (uint i = 0; !func(st, ta.tile + TileDiffXY(i, 0));) {
1584  /* the left side is unused? */
1585  if (++i == ta.w) {
1586  ta.tile += TileDiffXY(0, 1);
1587  ta.h--;
1588  goto restart;
1589  }
1590  }
1591 
1592  /* check the lower side, y = constant, x changes */
1593  for (uint i = 0; !func(st, ta.tile + TileDiffXY(i, ta.h - 1));) {
1594  /* the left side is unused? */
1595  if (++i == ta.w) {
1596  ta.h--;
1597  goto restart;
1598  }
1599  }
1600  } else {
1601  ta.Clear();
1602  }
1603 
1604  return ta;
1605 }
1606 
1607 static bool TileBelongsToRailStation(BaseStation *st, TileIndex tile)
1608 {
1609  return st->TileBelongsToRailStation(tile);
1610 }
1611 
1612 static void MakeRailStationAreaSmaller(BaseStation *st)
1613 {
1614  st->train_station = MakeStationAreaSmaller(st, st->train_station, TileBelongsToRailStation);
1615 }
1616 
1617 static bool TileBelongsToShipStation(BaseStation *st, TileIndex tile)
1618 {
1619  return IsDockTile(tile) && GetStationIndex(tile) == st->index;
1620 }
1621 
1622 static void MakeShipStationAreaSmaller(Station *st)
1623 {
1624  st->ship_station = MakeStationAreaSmaller(st, st->ship_station, TileBelongsToShipStation);
1625  UpdateStationDockingTiles(st);
1626 }
1627 
1628 static bool TileBelongsToRoadWaypointStation(BaseStation *st, TileIndex tile)
1629 {
1630  return IsRoadWaypointTile(tile) && GetStationIndex(tile) == st->index;
1631 }
1632 
1633 void MakeRoadWaypointStationAreaSmaller(BaseStation *st, TileArea &road_waypoint_area)
1634 {
1635  road_waypoint_area = MakeStationAreaSmaller(st, road_waypoint_area, TileBelongsToRoadWaypointStation);
1636 }
1637 
1648 template <class T>
1649 CommandCost RemoveFromRailBaseStation(TileArea ta, std::vector<T *> &affected_stations, DoCommandFlag flags, Money removal_cost, bool keep_rail)
1650 {
1651  /* Count of the number of tiles removed */
1652  int quantity = 0;
1653  CommandCost total_cost(EXPENSES_CONSTRUCTION);
1654  /* Accumulator for the errors seen during clearing. If no errors happen,
1655  * and the quantity is 0 there is no station. Otherwise it will be one
1656  * of the other error that got accumulated. */
1657  CommandCost error;
1658 
1659  /* Do the action for every tile into the area */
1660  for (TileIndex tile : ta) {
1661  /* Make sure the specified tile is a rail station */
1662  if (!HasStationTileRail(tile)) continue;
1663 
1664  /* If there is a vehicle on ground, do not allow to remove (flood) the tile */
1666  error.AddCost(ret);
1667  if (ret.Failed()) continue;
1668 
1669  /* Check ownership of station */
1670  T *st = T::GetByTile(tile);
1671  if (st == nullptr) continue;
1672 
1673  if (_current_company != OWNER_WATER) {
1674  ret = CheckOwnership(st->owner);
1675  error.AddCost(ret);
1676  if (ret.Failed()) continue;
1677  }
1678 
1679  /* If we reached here, the tile is valid so increase the quantity of tiles we will remove */
1680  quantity++;
1681 
1682  if (keep_rail || IsStationTileBlocked(tile)) {
1683  /* Don't refund the 'steel' of the track when we keep the
1684  * rail, or when the tile didn't have any rail at all. */
1685  total_cost.AddCost(-_price[PR_CLEAR_RAIL]);
1686  }
1687 
1688  if (flags & DC_EXEC) {
1689  /* read variables before the station tile is removed */
1690  uint specindex = GetCustomStationSpecIndex(tile);
1691  Track track = GetRailStationTrack(tile);
1692  Owner owner = GetTileOwner(tile);
1693  RailType rt = GetRailType(tile);
1694  Train *v = nullptr;
1695 
1696  if (HasStationReservation(tile)) {
1697  v = GetTrainForReservation(tile, track);
1698  if (v != nullptr) FreeTrainReservation(v);
1699  }
1700 
1701  bool build_rail = keep_rail && !IsStationTileBlocked(tile);
1702  if (!build_rail && !IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[rt]--;
1703 
1704  DoClearSquare(tile);
1705  DeleteNewGRFInspectWindow(GSF_STATIONS, tile.base());
1706  if (build_rail) MakeRailNormal(tile, owner, TrackToTrackBits(track), rt);
1707  Company::Get(owner)->infrastructure.station--;
1709 
1710  st->rect.AfterRemoveTile(st, tile);
1711  AddTrackToSignalBuffer(tile, track, owner);
1712  YapfNotifyTrackLayoutChange(tile, track);
1713 
1714  DeallocateSpecFromStation(st, specindex);
1715 
1716  include(affected_stations, st);
1717 
1718  if (v != nullptr) RestoreTrainReservation(v);
1719  }
1720  }
1721 
1722  if (quantity == 0) return error.Failed() ? error : CommandCost(STR_ERROR_THERE_IS_NO_STATION);
1723 
1724  for (T *st : affected_stations) {
1725 
1726  /* now we need to make the "spanned" area of the railway station smaller
1727  * if we deleted something at the edges.
1728  * we also need to adjust train_tile. */
1729  MakeRailStationAreaSmaller(st);
1730  UpdateStationSignCoord(st);
1731 
1732  /* if we deleted the whole station, delete the train facility. */
1733  if (st->train_station.tile == INVALID_TILE) {
1734  st->facilities &= ~FACIL_TRAIN;
1737  MarkCatchmentTilesDirty();
1738  st->UpdateVirtCoord();
1740  }
1741  }
1742 
1743  total_cost.AddCost(quantity * removal_cost);
1744  return total_cost;
1745 }
1746 
1757 {
1758  if (end == 0) end = start;
1759  if (start >= Map::Size() || end >= Map::Size()) return CMD_ERROR;
1760 
1761  TileArea ta(start, end);
1762  std::vector<Station *> affected_stations;
1763 
1764  CommandCost ret = RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_STATION_RAIL], keep_rail);
1765  if (ret.Failed()) return ret;
1766 
1767  /* Do all station specific functions here. */
1768  for (Station *st : affected_stations) {
1769 
1771  st->MarkTilesDirty(false);
1772  MarkCatchmentTilesDirty();
1773  st->RecomputeCatchment();
1774  }
1775 
1776  /* Now apply the rail cost to the number that we deleted */
1777  return ret;
1778 }
1779 
1790 {
1791  if (end == 0) end = start;
1792  if (start >= Map::Size() || end >= Map::Size()) return CMD_ERROR;
1793 
1794  TileArea ta(start, end);
1795  std::vector<Waypoint *> affected_stations;
1796 
1797  return RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_WAYPOINT_RAIL], keep_rail);
1798 }
1799 
1800 
1809 template <class T>
1811 {
1812  /* Current company owns the station? */
1813  if (_current_company != OWNER_WATER) {
1814  CommandCost ret = CheckOwnership(st->owner);
1815  if (ret.Failed()) return ret;
1816  }
1817 
1818  /* determine width and height of platforms */
1819  TileArea ta = st->train_station;
1820 
1821  assert(ta.w != 0 && ta.h != 0);
1822 
1824  /* clear all areas of the station */
1825  for (TileIndex tile : ta) {
1826  /* only remove tiles that are actually train station tiles */
1827  if (st->TileBelongsToRailStation(tile)) {
1828  std::vector<T*> affected_stations; // dummy
1829  CommandCost ret = RemoveFromRailBaseStation(TileArea(tile, 1, 1), affected_stations, flags, removal_cost, false);
1830  if (ret.Failed()) return ret;
1831  cost.AddCost(ret);
1832  }
1833  }
1834 
1835  return cost;
1836 }
1837 
1845 {
1846  /* if there is flooding, remove platforms tile by tile */
1847  if (_current_company == OWNER_WATER) {
1848  return Command<CMD_REMOVE_FROM_RAIL_STATION>::Do(DC_EXEC, tile, 0, false);
1849  }
1850 
1851  Station *st = Station::GetByTile(tile);
1852  CommandCost cost = RemoveRailStation(st, flags, _price[PR_CLEAR_STATION_RAIL]);
1853 
1854  if (flags & DC_EXEC) st->RecomputeCatchment();
1855 
1856  return cost;
1857 }
1858 
1866 {
1867  /* if there is flooding, remove waypoints tile by tile */
1868  if (_current_company == OWNER_WATER) {
1869  return Command<CMD_REMOVE_FROM_RAIL_WAYPOINT>::Do(DC_EXEC, tile, 0, false);
1870  }
1871 
1872  return RemoveRailStation(Waypoint::GetByTile(tile), flags, _price[PR_CLEAR_WAYPOINT_RAIL]);
1873 }
1874 
1875 
1881 static RoadStop **FindRoadStopSpot(bool truck_station, Station *st)
1882 {
1883  RoadStop **primary_stop = (truck_station) ? &st->truck_stops : &st->bus_stops;
1884 
1885  if (*primary_stop == nullptr) {
1886  /* we have no roadstop of the type yet, so write a "primary stop" */
1887  return primary_stop;
1888  } else {
1889  /* there are stops already, so append to the end of the list */
1890  RoadStop *stop = *primary_stop;
1891  while (stop->next != nullptr) stop = stop->next;
1892  return &stop->next;
1893  }
1894 }
1895 
1896 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags, int replacement_spec_index = -1);
1897 CommandCost RemoveRoadWaypointStop(TileIndex tile, DoCommandFlag flags, int replacement_spec_index = -1);
1898 
1908 static CommandCost FindJoiningRoadStop(StationID existing_stop, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
1909 {
1910  return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST>(existing_stop, station_to_join, adjacent, ta, st, [](const Station *) -> bool { return true; });
1911 }
1912 
1926 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)
1927 {
1928  uint invalid_dirs = 0;
1929  if (is_drive_through) {
1930  SetBit(invalid_dirs, AxisToDiagDir(axis));
1931  SetBit(invalid_dirs, ReverseDiagDir(AxisToDiagDir(axis)));
1932  } else {
1933  SetBit(invalid_dirs, ddir);
1934  }
1935 
1936  /* Check every tile in the area. */
1937  int allowed_z = -1;
1939  for (TileIndex cur_tile : tile_area) {
1940  CommandCost ret = CheckFlatLandRoadStop(cur_tile, allowed_z, flags, invalid_dirs, is_drive_through, station_type, axis, est, rt);
1941  if (ret.Failed()) return ret;
1942 
1943  bool is_preexisting_roadstop = IsTileType(cur_tile, MP_STATION) && IsAnyRoadStop(cur_tile);
1944 
1945  /* Only add costs if a stop doesn't already exist in the location */
1946  if (!is_preexisting_roadstop) {
1947  cost.AddCost(ret);
1948  cost.AddCost(unit_cost);
1949  }
1950  }
1951 
1952  return cost;
1953 }
1954 
1971 CommandCost CmdBuildRoadStop(DoCommandFlag flags, TileIndex tile, uint8_t width, uint8_t length, RoadStopType stop_type, bool is_drive_through,
1972  DiagDirection ddir, RoadType rt, RoadStopClassID spec_class, uint16_t spec_index, StationID station_to_join, bool adjacent)
1973 {
1974  if (!ValParamRoadType(rt) || !IsValidDiagDirection(ddir) || stop_type >= ROADSTOP_END) return CMD_ERROR;
1975  bool reuse = (station_to_join != NEW_STATION);
1976  if (!reuse) station_to_join = INVALID_STATION;
1977  bool distant_join = (station_to_join != INVALID_STATION);
1978 
1979  /* Check if the given station class is valid */
1980  if (static_cast<uint>(spec_class) >= RoadStopClass::GetClassCount()) return CMD_ERROR;
1981  const RoadStopClass *cls = RoadStopClass::Get(spec_class);
1982  if (IsWaypointClass(*cls)) return CMD_ERROR;
1983  if (spec_index >= cls->GetSpecCount()) return CMD_ERROR;
1984 
1985  const RoadStopSpec *roadstopspec = cls->GetSpec(spec_index);
1986  if (roadstopspec != nullptr) {
1987  if (stop_type == ROADSTOP_TRUCK && roadstopspec->stop_type != ROADSTOPTYPE_FREIGHT && roadstopspec->stop_type != ROADSTOPTYPE_ALL) return CMD_ERROR;
1988  if (stop_type == ROADSTOP_BUS && roadstopspec->stop_type != ROADSTOPTYPE_PASSENGER && roadstopspec->stop_type != ROADSTOPTYPE_ALL) return CMD_ERROR;
1989  if (!is_drive_through && HasBit(roadstopspec->flags, RSF_DRIVE_THROUGH_ONLY)) return CMD_ERROR;
1990  }
1991 
1992  /* Check if the requested road stop is too big */
1993  if (width > _settings_game.station.station_spread || length > _settings_game.station.station_spread) return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
1994  /* Check for incorrect width / length. */
1995  if (width == 0 || length == 0) return CMD_ERROR;
1996  /* Check if the first tile and the last tile are valid */
1997  if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, length - 1) == INVALID_TILE) return CMD_ERROR;
1998 
1999  TileArea roadstop_area(tile, width, length);
2000 
2001  if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2002 
2003  /* Trams only have drive through stops */
2004  if (!is_drive_through && RoadTypeIsTram(rt)) return CMD_ERROR;
2005 
2006  Axis axis = DiagDirToAxis(ddir);
2007 
2008  CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
2009  if (ret.Failed()) return ret;
2010 
2011  bool is_truck_stop = stop_type != ROADSTOP_BUS;
2012 
2013  /* Total road stop cost. */
2014  Money unit_cost;
2015  if (roadstopspec != nullptr) {
2016  unit_cost = roadstopspec->GetBuildCost(is_truck_stop ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS);
2017  } else {
2018  unit_cost = _price[is_truck_stop ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS];
2019  }
2020  StationID est = INVALID_STATION;
2021  CommandCost cost = CalculateRoadStopCost(roadstop_area, flags, is_drive_through, is_truck_stop ? STATION_TRUCK : STATION_BUS, axis, ddir, &est, rt, unit_cost);
2022  if (cost.Failed()) return cost;
2023 
2024  Station *st = nullptr;
2025  ret = FindJoiningRoadStop(est, station_to_join, adjacent, roadstop_area, &st);
2026  if (ret.Failed()) return ret;
2027 
2028  /* Check if this number of road stops can be allocated. */
2029  if (!RoadStop::CanAllocateItem(static_cast<size_t>(roadstop_area.w) * roadstop_area.h)) return_cmd_error(is_truck_stop ? STR_ERROR_TOO_MANY_TRUCK_STOPS : STR_ERROR_TOO_MANY_BUS_STOPS);
2030 
2031  ret = BuildStationPart(&st, flags, reuse, roadstop_area, STATIONNAMING_ROAD);
2032  if (ret.Failed()) return ret;
2033 
2034  /* Check if we can allocate a custom stationspec to this station */
2035  int specindex = AllocateSpecToRoadStop(roadstopspec, st, (flags & DC_EXEC) != 0);
2036  if (specindex == -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS);
2037 
2038  if (roadstopspec != nullptr) {
2039  /* Perform NewGRF checks */
2040 
2041  /* Check if the road stop is buildable */
2042  if (HasBit(roadstopspec->callback_mask, CBM_ROAD_STOP_AVAIL)) {
2043  uint16_t cb_res = GetRoadStopCallback(CBID_STATION_AVAILABILITY, 0, 0, roadstopspec, nullptr, INVALID_TILE, rt, is_truck_stop ? STATION_TRUCK : STATION_BUS, 0);
2044  if (cb_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(roadstopspec->grf_prop.grffile, CBID_STATION_AVAILABILITY, cb_res)) return CMD_ERROR;
2045  }
2046  }
2047 
2048  if (flags & DC_EXEC) {
2049  /* Check every tile in the area. */
2050  for (TileIndex cur_tile : roadstop_area) {
2051  /* Get existing road types and owners before any tile clearing */
2052  RoadType road_rt = MayHaveRoad(cur_tile) ? GetRoadType(cur_tile, RTT_ROAD) : INVALID_ROADTYPE;
2053  RoadType tram_rt = MayHaveRoad(cur_tile) ? GetRoadType(cur_tile, RTT_TRAM) : INVALID_ROADTYPE;
2054  Owner road_owner = road_rt != INVALID_ROADTYPE ? GetRoadOwner(cur_tile, RTT_ROAD) : _current_company;
2055  Owner tram_owner = tram_rt != INVALID_ROADTYPE ? GetRoadOwner(cur_tile, RTT_TRAM) : _current_company;
2056 
2057  if (IsTileType(cur_tile, MP_STATION) && IsStationRoadStop(cur_tile)) {
2058  RemoveRoadStop(cur_tile, flags, specindex);
2059  }
2060 
2061  if (roadstopspec != nullptr) {
2062  /* Include this road stop spec's animation trigger bitmask
2063  * in the station's cached copy. */
2064  st->cached_roadstop_anim_triggers |= roadstopspec->animation.triggers;
2065  }
2066 
2067  RoadStop *road_stop = new RoadStop(cur_tile);
2068  /* Insert into linked list of RoadStops. */
2069  RoadStop **currstop = FindRoadStopSpot(is_truck_stop, st);
2070  *currstop = road_stop;
2071 
2072  if (is_truck_stop) {
2073  st->truck_station.Add(cur_tile);
2074  } else {
2075  st->bus_station.Add(cur_tile);
2076  }
2077 
2078  /* Initialize an empty station. */
2079  st->AddFacility(is_truck_stop ? FACIL_TRUCK_STOP : FACIL_BUS_STOP, cur_tile);
2080 
2081  st->rect.BeforeAddTile(cur_tile, StationRect::ADD_TRY);
2082 
2083  RoadStopType rs_type = is_truck_stop ? ROADSTOP_TRUCK : ROADSTOP_BUS;
2084  if (is_drive_through) {
2085  /* Update company infrastructure counts. If the current tile is a normal road tile, remove the old
2086  * bits first. */
2087  if (IsNormalRoadTile(cur_tile)) {
2088  UpdateCompanyRoadInfrastructure(road_rt, road_owner, -(int)CountBits(GetRoadBits(cur_tile, RTT_ROAD)));
2089  UpdateCompanyRoadInfrastructure(tram_rt, tram_owner, -(int)CountBits(GetRoadBits(cur_tile, RTT_TRAM)));
2090  }
2091 
2092  if (road_rt == INVALID_ROADTYPE && RoadTypeIsRoad(rt)) road_rt = rt;
2093  if (tram_rt == INVALID_ROADTYPE && RoadTypeIsTram(rt)) tram_rt = rt;
2094 
2095  MakeDriveThroughRoadStop(cur_tile, st->owner, road_owner, tram_owner, st->index, (rs_type == ROADSTOP_BUS ? STATION_BUS : STATION_TRUCK), road_rt, tram_rt, axis);
2096  road_stop->MakeDriveThrough();
2097  } else {
2098  if (road_rt == INVALID_ROADTYPE && RoadTypeIsRoad(rt)) road_rt = rt;
2099  if (tram_rt == INVALID_ROADTYPE && RoadTypeIsTram(rt)) tram_rt = rt;
2100  MakeRoadStop(cur_tile, st->owner, st->index, rs_type, road_rt, tram_rt, ddir);
2101  }
2104  Company::Get(st->owner)->infrastructure.station++;
2105 
2106  SetCustomRoadStopSpecIndex(cur_tile, specindex);
2107  if (roadstopspec != nullptr) {
2108  st->SetRoadStopRandomBits(cur_tile, GB(Random(), 0, 8));
2109  TriggerRoadStopAnimation(st, cur_tile, SAT_BUILT);
2110  }
2111 
2112  MarkTileDirtyByTile(cur_tile);
2113  }
2114 
2115  if (st != nullptr) {
2116  st->AfterStationTileSetChange(true, is_truck_stop ? STATION_TRUCK: STATION_BUS);
2117  }
2118  }
2119  return cost;
2120 }
2121 
2122 
2123 static Vehicle *ClearRoadStopStatusEnum(Vehicle *v, void *)
2124 {
2125  if (v->type == VEH_ROAD) {
2126  /* Okay... we are a road vehicle on a drive through road stop.
2127  * But that road stop has just been removed, so we need to make
2128  * sure we are in a valid state... however, vehicles can also
2129  * turn on road stop tiles, so only clear the 'road stop' state
2130  * bits and only when the state was 'in road stop', otherwise
2131  * we'll end up clearing the turn around bits. */
2132  RoadVehicle *rv = RoadVehicle::From(v);
2134  }
2135 
2136  return nullptr;
2137 }
2138 
2139 
2147 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags, int replacement_spec_index)
2148 {
2149  Station *st = Station::GetByTile(tile);
2150 
2151  if (_current_company != OWNER_WATER) {
2152  CommandCost ret = CheckOwnership(st->owner);
2153  if (ret.Failed()) return ret;
2154  }
2155 
2156  bool is_truck = IsTruckStop(tile);
2157 
2158  RoadStop **primary_stop;
2159  RoadStop *cur_stop;
2160  if (is_truck) { // truck stop
2161  primary_stop = &st->truck_stops;
2162  cur_stop = RoadStop::GetByTile(tile, ROADSTOP_TRUCK);
2163  } else {
2164  primary_stop = &st->bus_stops;
2165  cur_stop = RoadStop::GetByTile(tile, ROADSTOP_BUS);
2166  }
2167 
2168  assert(cur_stop != nullptr);
2169 
2170  /* don't do the check for drive-through road stops when company bankrupts */
2171  if (IsDriveThroughStopTile(tile) && (flags & DC_BANKRUPT)) {
2172  /* remove the 'going through road stop' status from all vehicles on that tile */
2173  if (flags & DC_EXEC) FindVehicleOnPos(tile, nullptr, &ClearRoadStopStatusEnum);
2174  } else {
2176  if (ret.Failed()) return ret;
2177  }
2178 
2179  const RoadStopSpec *spec = GetRoadStopSpec(tile);
2180 
2181  if (flags & DC_EXEC) {
2182  if (*primary_stop == cur_stop) {
2183  /* removed the first stop in the list */
2184  *primary_stop = cur_stop->next;
2185  /* removed the only stop? */
2186  if (*primary_stop == nullptr) {
2187  st->facilities &= (is_truck ? ~FACIL_TRUCK_STOP : ~FACIL_BUS_STOP);
2189  }
2190  } else {
2191  /* tell the predecessor in the list to skip this stop */
2192  RoadStop *pred = *primary_stop;
2193  while (pred->next != cur_stop) pred = pred->next;
2194  pred->next = cur_stop->next;
2195  }
2196 
2197  /* Update company infrastructure counts. */
2198  for (RoadTramType rtt : _roadtramtypes) {
2199  RoadType rt = GetRoadType(tile, rtt);
2200  UpdateCompanyRoadInfrastructure(rt, GetRoadOwner(tile, rtt), -static_cast<int>(ROAD_STOP_TRACKBIT_FACTOR));
2201  }
2202 
2203  Company::Get(st->owner)->infrastructure.station--;
2205 
2206  DeleteAnimatedTile(tile);
2207 
2208  uint specindex = GetCustomRoadStopSpecIndex(tile);
2209 
2210  DeleteNewGRFInspectWindow(GSF_ROADSTOPS, tile.base());
2211 
2212  if (IsDriveThroughStopTile(tile)) {
2213  /* Clears the tile for us */
2214  cur_stop->ClearDriveThrough();
2215  } else {
2216  DoClearSquare(tile);
2217  }
2218 
2219  delete cur_stop;
2220 
2221  /* Make sure no vehicle is going to the old roadstop. Narrow the search to any road vehicles with an order to
2222  * this station, then look for any currently heading to the tile. */
2223  StationID station_id = st->index;
2225  [](const Vehicle *v) { return v->type == VEH_ROAD; },
2226  [station_id](const Order *order) { return order->IsType(OT_GOTO_STATION) && order->GetDestination() == station_id; },
2227  [station_id, tile](Vehicle *v) {
2228  if (v->current_order.IsType(OT_GOTO_STATION) && v->dest_tile == tile) {
2229  v->SetDestTile(v->GetOrderStationLocation(station_id));
2230  }
2231  }
2232  );
2233 
2234  st->rect.AfterRemoveTile(st, tile);
2235 
2236  if (replacement_spec_index < 0) st->AfterStationTileSetChange(false, is_truck ? STATION_TRUCK: STATION_BUS);
2237 
2238  st->RemoveRoadStopTileData(tile);
2239  if ((int)specindex != replacement_spec_index) DeallocateSpecFromRoadStop(st, specindex);
2240 
2241  /* Update the tile area of the truck/bus stop */
2242  if (is_truck) {
2243  st->truck_station.Clear();
2244  for (const RoadStop *rs = st->truck_stops; rs != nullptr; rs = rs->next) st->truck_station.Add(rs->xy);
2245  } else {
2246  st->bus_station.Clear();
2247  for (const RoadStop *rs = st->bus_stops; rs != nullptr; rs = rs->next) st->bus_station.Add(rs->xy);
2248  }
2249  }
2250 
2251  Price category = is_truck ? PR_CLEAR_STATION_TRUCK : PR_CLEAR_STATION_BUS;
2252  return CommandCost(EXPENSES_CONSTRUCTION, spec != nullptr ? spec->GetClearCost(category) : _price[category]);
2253 }
2254 
2262 CommandCost RemoveRoadWaypointStop(TileIndex tile, DoCommandFlag flags, int replacement_spec_index)
2263 {
2264  Waypoint *wp = Waypoint::GetByTile(tile);
2265 
2266  if (_current_company != OWNER_WATER) {
2267  CommandCost ret = CheckOwnership(wp->owner);
2268  if (ret.Failed()) return ret;
2269  }
2270 
2271  /* Ignore vehicles when the company goes bankrupt. The road will remain, any vehicles going to the waypoint will be removed. */
2272  if (!(flags & DC_BANKRUPT)) {
2274  if (ret.Failed()) return ret;
2275  }
2276 
2277  const RoadStopSpec *spec = GetRoadStopSpec(tile);
2278 
2279  if (flags & DC_EXEC) {
2280  /* Update company infrastructure counts. */
2281  for (RoadTramType rtt : _roadtramtypes) {
2282  RoadType rt = GetRoadType(tile, rtt);
2283  UpdateCompanyRoadInfrastructure(rt, GetRoadOwner(tile, rtt), -static_cast<int>(ROAD_STOP_TRACKBIT_FACTOR));
2284  }
2285 
2286  Company::Get(wp->owner)->infrastructure.station--;
2288 
2289  DeleteAnimatedTile(tile);
2290 
2291  uint specindex = GetCustomRoadStopSpecIndex(tile);
2292 
2293  DeleteNewGRFInspectWindow(GSF_ROADSTOPS, tile.base());
2294 
2295  DoClearSquare(tile);
2296 
2297  wp->rect.AfterRemoveTile(wp, tile);
2298 
2299  wp->RemoveRoadStopTileData(tile);
2300  if ((int)specindex != replacement_spec_index) DeallocateSpecFromRoadStop(wp, specindex);
2301 
2302  if (replacement_spec_index < 0) {
2303  MakeRoadWaypointStationAreaSmaller(wp, wp->road_waypoint_area);
2304 
2305  UpdateStationSignCoord(wp);
2306 
2307  /* if we deleted the whole waypoint, delete the road facility. */
2308  if (wp->road_waypoint_area.tile == INVALID_TILE) {
2311  wp->UpdateVirtCoord();
2313  }
2314  }
2315  }
2316 
2317  return CommandCost(EXPENSES_CONSTRUCTION, spec != nullptr ? spec->GetClearCost(PR_CLEAR_STATION_TRUCK) : _price[PR_CLEAR_STATION_TRUCK]);
2318 }
2319 
2328 static CommandCost RemoveGenericRoadStop(DoCommandFlag flags, const TileArea &roadstop_area, StationType station_type, bool remove_road)
2329 {
2331  CommandCost last_error(STR_ERROR_THERE_IS_NO_STATION);
2332  bool had_success = false;
2333 
2334  for (TileIndex cur_tile : roadstop_area) {
2335  /* Make sure the specified tile is a road stop of the correct type */
2336  if (!IsTileType(cur_tile, MP_STATION) || !IsAnyRoadStop(cur_tile) || GetStationType(cur_tile) != station_type) continue;
2337 
2338  /* Save information on to-be-restored roads before the stop is removed. */
2339  RoadBits road_bits = ROAD_NONE;
2340  RoadType road_type[] = { INVALID_ROADTYPE, INVALID_ROADTYPE };
2341  Owner road_owner[] = { OWNER_NONE, OWNER_NONE };
2342  if (IsDriveThroughStopTile(cur_tile)) {
2343  for (RoadTramType rtt : _roadtramtypes) {
2344  road_type[rtt] = GetRoadType(cur_tile, rtt);
2345  if (road_type[rtt] == INVALID_ROADTYPE) continue;
2346  road_owner[rtt] = GetRoadOwner(cur_tile, rtt);
2347  /* If we don't want to preserve our roads then restore only roads of others. */
2348  if (remove_road && road_owner[rtt] == _current_company) road_type[rtt] = INVALID_ROADTYPE;
2349  }
2350  road_bits = AxisToRoadBits(DiagDirToAxis(GetRoadStopDir(cur_tile)));
2351  }
2352 
2353  CommandCost ret;
2354  if (station_type == STATION_ROADWAYPOINT) {
2355  ret = RemoveRoadWaypointStop(cur_tile, flags);
2356  } else {
2357  ret = RemoveRoadStop(cur_tile, flags);
2358  }
2359  if (ret.Failed()) {
2360  last_error = ret;
2361  continue;
2362  }
2363  cost.AddCost(ret);
2364  had_success = true;
2365 
2366  /* Restore roads. */
2367  if ((flags & DC_EXEC) && (road_type[RTT_ROAD] != INVALID_ROADTYPE || road_type[RTT_TRAM] != INVALID_ROADTYPE)) {
2368  MakeRoadNormal(cur_tile, road_bits, road_type[RTT_ROAD], road_type[RTT_TRAM], ClosestTownFromTile(cur_tile, UINT_MAX)->index,
2369  road_owner[RTT_ROAD], road_owner[RTT_TRAM]);
2370 
2371  /* Update company infrastructure counts. */
2372  int count = CountBits(road_bits);
2373  UpdateCompanyRoadInfrastructure(road_type[RTT_ROAD], road_owner[RTT_ROAD], count);
2374  UpdateCompanyRoadInfrastructure(road_type[RTT_TRAM], road_owner[RTT_TRAM], count);
2375  }
2376  }
2377 
2378  return had_success ? cost : last_error;
2379 }
2380 
2391 CommandCost CmdRemoveRoadStop(DoCommandFlag flags, TileIndex tile, uint8_t width, uint8_t height, RoadStopType stop_type, bool remove_road)
2392 {
2393  if (stop_type >= ROADSTOP_END) return CMD_ERROR;
2394  /* Check for incorrect width / height. */
2395  if (width == 0 || height == 0) return CMD_ERROR;
2396  /* Check if the first tile and the last tile are valid */
2397  if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, height - 1) == INVALID_TILE) return CMD_ERROR;
2398  /* Bankrupting company is not supposed to remove roads, there may be road vehicles. */
2399  if (remove_road && (flags & DC_BANKRUPT)) return CMD_ERROR;
2400 
2401  TileArea roadstop_area(tile, width, height);
2402 
2403  return RemoveGenericRoadStop(flags, roadstop_area, stop_type == ROADSTOP_BUS ? STATION_BUS : STATION_TRUCK, remove_road);
2404 }
2405 
2414 {
2415  if (end == 0) end = start;
2416  if (start >= Map::Size() || end >= Map::Size()) return CMD_ERROR;
2417 
2418  TileArea roadstop_area(start, end);
2419 
2420  return RemoveGenericRoadStop(flags, roadstop_area, STATION_ROADWAYPOINT, false);
2421 }
2422 
2431 uint8_t GetAirportNoiseLevelForDistance(const AirportSpec *as, uint distance)
2432 {
2433  /* 0 cannot be accounted, and 1 is the lowest that can be reduced from town.
2434  * So no need to go any further*/
2435  if (as->noise_level < 2) return as->noise_level;
2436 
2437  /* The steps for measuring noise reduction are based on the "magical" (and arbitrary) 8 base distance
2438  * adding the town_council_tolerance 4 times, as a way to graduate, depending of the tolerance.
2439  * Basically, it says that the less tolerant a town is, the bigger the distance before
2440  * an actual decrease can be granted */
2441  uint8_t town_tolerance_distance = 8 + (_settings_game.difficulty.town_council_tolerance * 4);
2442 
2443  /* now, we want to have the distance segmented using the distance judged bareable by town
2444  * This will give us the coefficient of reduction the distance provides. */
2445  uint noise_reduction = distance / town_tolerance_distance;
2446 
2447  /* If the noise reduction equals the airport noise itself, don't give it for free.
2448  * Otherwise, simply reduce the airport's level. */
2449  return noise_reduction >= as->noise_level ? 1 : as->noise_level - noise_reduction;
2450 }
2451 
2462 Town *AirportGetNearestTown(const AirportSpec *as, Direction rotation, TileIndex tile, TileIterator &&it, uint &mindist)
2463 {
2464  assert(Town::GetNumItems() > 0);
2465 
2466  Town *nearest = nullptr;
2467 
2468  auto width = as->size_x;
2469  auto height = as->size_y;
2470  if (rotation == DIR_E || rotation == DIR_W) std::swap(width, height);
2471 
2472  uint perimeter_min_x = TileX(tile);
2473  uint perimeter_min_y = TileY(tile);
2474  uint perimeter_max_x = perimeter_min_x + width - 1;
2475  uint perimeter_max_y = perimeter_min_y + height - 1;
2476 
2477  mindist = UINT_MAX - 1; // prevent overflow
2478 
2479  for (TileIndex cur_tile = *it; cur_tile != INVALID_TILE; cur_tile = ++it) {
2480  assert(IsInsideBS(TileX(cur_tile), perimeter_min_x, width));
2481  assert(IsInsideBS(TileY(cur_tile), perimeter_min_y, height));
2482  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) {
2483  Town *t = CalcClosestTownFromTile(cur_tile, mindist + 1);
2484  if (t == nullptr) continue;
2485 
2486  uint dist = DistanceManhattan(t->xy, cur_tile);
2487  if (dist == mindist && t->index < nearest->index) nearest = t;
2488  if (dist < mindist) {
2489  nearest = t;
2490  mindist = dist;
2491  }
2492  }
2493  }
2494 
2495  return nearest;
2496 }
2497 
2505 static Town *AirportGetNearestTown(const Station *st, uint &mindist)
2506 {
2507  return AirportGetNearestTown(st->airport.GetSpec(), st->airport.rotation, st->airport.tile, AirportTileIterator(st), mindist);
2508 }
2509 
2510 
2513 {
2514  for (Town *t : Town::Iterate()) t->noise_reached = 0;
2515 
2516  for (const Station *st : Station::Iterate()) {
2517  if (st->airport.tile != INVALID_TILE && st->airport.type != AT_OILRIG) {
2518  uint dist;
2519  Town *nearest = AirportGetNearestTown(st, dist);
2520  nearest->noise_reached += GetAirportNoiseLevelForDistance(st->airport.GetSpec(), dist);
2521  }
2522  }
2523 }
2524 
2535 CommandCost CmdBuildAirport(DoCommandFlag flags, TileIndex tile, uint8_t airport_type, uint8_t layout, StationID station_to_join, bool allow_adjacent)
2536 {
2537  bool reuse = (station_to_join != NEW_STATION);
2538  if (!reuse) station_to_join = INVALID_STATION;
2539  bool distant_join = (station_to_join != INVALID_STATION);
2540 
2541  if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2542 
2543  if (airport_type >= NUM_AIRPORTS) return CMD_ERROR;
2544 
2545  CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
2546  if (ret.Failed()) return ret;
2547 
2548  /* Check if a valid, buildable airport was chosen for construction */
2549  const AirportSpec *as = AirportSpec::Get(airport_type);
2550  if (!as->IsAvailable() || layout >= as->layouts.size()) return CMD_ERROR;
2551  if (!as->IsWithinMapBounds(layout, tile)) return CMD_ERROR;
2552 
2553  Direction rotation = as->layouts[layout].rotation;
2554  int w = as->size_x;
2555  int h = as->size_y;
2556  if (rotation == DIR_E || rotation == DIR_W) Swap(w, h);
2557  TileArea airport_area = TileArea(tile, w, h);
2558 
2560  return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
2561  }
2562 
2563  AirportTileTableIterator tile_iter(as->layouts[layout].tiles.data(), tile);
2564  CommandCost cost = CheckFlatLandAirport(tile_iter, flags);
2565  if (cost.Failed()) return cost;
2566 
2567  /* The noise level is the noise from the airport and reduce it to account for the distance to the town center. */
2568  uint dist;
2569  Town *nearest = AirportGetNearestTown(as, rotation, tile, std::move(tile_iter), dist);
2570  uint newnoise_level = GetAirportNoiseLevelForDistance(as, dist);
2571 
2572  /* Check if local auth would allow a new airport */
2573  StringID authority_refuse_message = STR_NULL;
2574  Town *authority_refuse_town = nullptr;
2575 
2577  /* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
2578  if ((nearest->noise_reached + newnoise_level) > nearest->MaxTownNoise()) {
2579  authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE;
2580  authority_refuse_town = nearest;
2581  }
2582  } else if (_settings_game.difficulty.town_council_tolerance != TOWN_COUNCIL_PERMISSIVE) {
2583  Town *t = ClosestTownFromTile(tile, UINT_MAX);
2584  uint num = 0;
2585  for (const Station *st : Station::Iterate()) {
2586  if (st->town == t && (st->facilities & FACIL_AIRPORT) && st->airport.type != AT_OILRIG) num++;
2587  }
2588  if (num >= 2) {
2589  authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT;
2590  authority_refuse_town = t;
2591  }
2592  }
2593 
2594  if (authority_refuse_message != STR_NULL) {
2595  SetDParam(0, authority_refuse_town->index);
2596  return_cmd_error(authority_refuse_message);
2597  }
2598 
2599  Station *st = nullptr;
2600  ret = FindJoiningStation(INVALID_STATION, station_to_join, allow_adjacent, airport_area, &st);
2601  if (ret.Failed()) return ret;
2602 
2603  /* Distant join */
2604  if (st == nullptr && distant_join) st = Station::GetIfValid(station_to_join);
2605 
2606  ret = BuildStationPart(&st, flags, reuse, airport_area, (GetAirport(airport_type)->flags & AirportFTAClass::AIRPLANES) ? STATIONNAMING_AIRPORT : STATIONNAMING_HELIPORT);
2607  if (ret.Failed()) return ret;
2608 
2609  if (st != nullptr && st->airport.tile != INVALID_TILE) {
2610  return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT);
2611  }
2612 
2613  for (AirportTileTableIterator iter(as->layouts[layout].tiles.data(), tile); iter != INVALID_TILE; ++iter) {
2614  cost.AddCost(_price[PR_BUILD_STATION_AIRPORT]);
2615  }
2616 
2617  if (flags & DC_EXEC) {
2618  /* Always add the noise, so there will be no need to recalculate when option toggles */
2619  nearest->noise_reached += newnoise_level;
2620 
2621  st->AddFacility(FACIL_AIRPORT, tile);
2622  st->airport.type = airport_type;
2623  st->airport.layout = layout;
2624  st->airport.flags = 0;
2625  st->airport.rotation = rotation;
2626 
2627  st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TRY);
2628 
2629  for (AirportTileTableIterator iter(as->layouts[layout].tiles.data(), tile); iter != INVALID_TILE; ++iter) {
2630  Tile t(iter);
2631  MakeAirport(t, st->owner, st->index, iter.GetStationGfx(), WATER_CLASS_INVALID);
2632  SetStationTileRandomBits(t, GB(Random(), 0, 4));
2633  st->airport.Add(iter);
2634 
2636  }
2637 
2638  /* Only call the animation trigger after all tiles have been built */
2639  for (AirportTileTableIterator iter(as->layouts[layout].tiles.data(), tile); iter != INVALID_TILE; ++iter) {
2640  AirportTileAnimationTrigger(st, iter, AAT_BUILT);
2641  }
2642 
2644 
2645  Company::Get(st->owner)->infrastructure.airport++;
2646 
2647  st->AfterStationTileSetChange(true, STATION_AIRPORT);
2649 
2651  SetWindowDirty(WC_TOWN_VIEW, nearest->index);
2652  }
2653  }
2654 
2655  return cost;
2656 }
2657 
2665 {
2666  Station *st = Station::GetByTile(tile);
2667 
2668  if (_current_company != OWNER_WATER) {
2669  CommandCost ret = CheckOwnership(st->owner);
2670  if (ret.Failed()) return ret;
2671  }
2672 
2673  tile = st->airport.tile;
2674 
2676 
2677  for (const Aircraft *a : Aircraft::Iterate()) {
2678  if (!a->IsNormalAircraft()) continue;
2679  if (a->targetairport == st->index && a->state != FLYING) {
2680  return_cmd_error(STR_ERROR_AIRCRAFT_IN_THE_WAY);
2681  }
2682  }
2683 
2684  if (flags & DC_EXEC) {
2685  for (uint i = 0; i < st->airport.GetNumHangars(); ++i) {
2686  TileIndex tile_cur = st->airport.GetHangarTile(i);
2687  OrderBackup::Reset(tile_cur, false);
2688  CloseWindowById(WC_VEHICLE_DEPOT, tile_cur);
2689  }
2690 
2691  /* The noise level is the noise from the airport and reduce it to account for the distance to the town center.
2692  * And as for construction, always remove it, even if the setting is not set, in order to avoid the
2693  * need of recalculation */
2694  uint dist;
2695  Town *nearest = AirportGetNearestTown(st, dist);
2697 
2699  SetWindowDirty(WC_TOWN_VIEW, nearest->index);
2700  }
2701  }
2702 
2703  for (TileIndex tile_cur : st->airport) {
2704  if (!st->TileBelongsToAirport(tile_cur)) continue;
2705 
2706  CommandCost ret = EnsureNoVehicleOnGround(tile_cur);
2707  if (ret.Failed()) return ret;
2708 
2709  cost.AddCost(_price[PR_CLEAR_STATION_AIRPORT]);
2710 
2711  if (flags & DC_EXEC) {
2712  DeleteAnimatedTile(tile_cur);
2713  DoClearSquare(tile_cur);
2714  DeleteNewGRFInspectWindow(GSF_AIRPORTTILES, tile_cur.base());
2715  }
2716  }
2717 
2718  if (flags & DC_EXEC) {
2719  /* Clear the persistent storage. */
2720  delete st->airport.psa;
2721 
2722  st->rect.AfterRemoveRect(st, st->airport);
2723 
2724  st->airport.Clear();
2725  st->facilities &= ~FACIL_AIRPORT;
2727 
2729 
2730  Company::Get(st->owner)->infrastructure.airport--;
2731 
2732  st->AfterStationTileSetChange(false, STATION_AIRPORT);
2733 
2734  DeleteNewGRFInspectWindow(GSF_AIRPORTS, st->index);
2735  }
2736 
2737  return cost;
2738 }
2739 
2746 CommandCost CmdOpenCloseAirport(DoCommandFlag flags, StationID station_id)
2747 {
2748  if (!Station::IsValidID(station_id)) return CMD_ERROR;
2749  Station *st = Station::Get(station_id);
2750 
2751  if (!(st->facilities & FACIL_AIRPORT) || st->owner == OWNER_NONE) return CMD_ERROR;
2752 
2753  CommandCost ret = CheckOwnership(st->owner);
2754  if (ret.Failed()) return ret;
2755 
2756  if (flags & DC_EXEC) {
2759  }
2760  return CommandCost();
2761 }
2762 
2769 bool HasStationInUse(StationID station, bool include_company, CompanyID company)
2770 {
2771  for (const OrderList *orderlist : OrderList::Iterate()) {
2772  const Vehicle *v = orderlist->GetFirstSharedVehicle();
2773  assert(v != nullptr);
2774  if ((v->owner == company) != include_company) continue;
2775 
2776  for (const Order *order = orderlist->GetFirstOrder(); order != nullptr; order = order->next) {
2777  if (order->GetDestination() == station && (order->IsType(OT_GOTO_STATION) || order->IsType(OT_GOTO_WAYPOINT))) {
2778  return true;
2779  }
2780  }
2781  }
2782  return false;
2783 }
2784 
2785 static const TileIndexDiffC _dock_tileoffs_chkaround[] = {
2786  {-1, 0},
2787  { 0, 0},
2788  { 0, 0},
2789  { 0, -1}
2790 };
2791 static const uint8_t _dock_w_chk[4] = { 2, 1, 2, 1 };
2792 static const uint8_t _dock_h_chk[4] = { 1, 2, 1, 2 };
2793 
2802 CommandCost CmdBuildDock(DoCommandFlag flags, TileIndex tile, StationID station_to_join, bool adjacent)
2803 {
2804  bool reuse = (station_to_join != NEW_STATION);
2805  if (!reuse) station_to_join = INVALID_STATION;
2806  bool distant_join = (station_to_join != INVALID_STATION);
2807 
2808  if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2809 
2811  if (direction == INVALID_DIAGDIR) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2812  direction = ReverseDiagDir(direction);
2813 
2814  /* Docks cannot be placed on rapids */
2815  if (HasTileWaterGround(tile)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2816 
2817  CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
2818  if (ret.Failed()) return ret;
2819 
2820  if (IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
2821 
2822  CommandCost cost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_STATION_DOCK]);
2823  ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile);
2824  if (ret.Failed()) return ret;
2825  cost.AddCost(ret);
2826 
2827  TileIndex tile_cur = tile + TileOffsByDiagDir(direction);
2828 
2829  if (!HasTileWaterGround(tile_cur) || !IsTileFlat(tile_cur)) {
2830  return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2831  }
2832 
2833  if (IsBridgeAbove(tile_cur)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
2834 
2835  /* Get the water class of the water tile before it is cleared.*/
2836  WaterClass wc = GetWaterClass(tile_cur);
2837 
2838  bool add_cost = !IsWaterTile(tile_cur);
2839  ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile_cur);
2840  if (ret.Failed()) return ret;
2841  if (add_cost) cost.AddCost(ret);
2842 
2843  tile_cur += TileOffsByDiagDir(direction);
2844  if (!IsTileType(tile_cur, MP_WATER) || !IsTileFlat(tile_cur)) {
2845  return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2846  }
2847 
2848  TileArea dock_area = TileArea(tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
2849  _dock_w_chk[direction], _dock_h_chk[direction]);
2850 
2851  /* middle */
2852  Station *st = nullptr;
2853  ret = FindJoiningStation(INVALID_STATION, station_to_join, adjacent, dock_area, &st);
2854  if (ret.Failed()) return ret;
2855 
2856  /* Distant join */
2857  if (st == nullptr && distant_join) st = Station::GetIfValid(station_to_join);
2858 
2859  ret = BuildStationPart(&st, flags, reuse, dock_area, STATIONNAMING_DOCK);
2860  if (ret.Failed()) return ret;
2861 
2862  if (flags & DC_EXEC) {
2863  st->ship_station.Add(tile);
2864  TileIndex flat_tile = tile + TileOffsByDiagDir(direction);
2865  st->ship_station.Add(flat_tile);
2866  st->AddFacility(FACIL_DOCK, tile);
2867 
2868  st->rect.BeforeAddRect(dock_area.tile, dock_area.w, dock_area.h, StationRect::ADD_TRY);
2869 
2870  /* If the water part of the dock is on a canal, update infrastructure counts.
2871  * This is needed as we've cleared that tile before.
2872  * Clearing object tiles may result in water tiles which are already accounted for in the water infrastructure total.
2873  * See: MakeWaterKeepingClass() */
2874  if (wc == WATER_CLASS_CANAL && !(HasTileWaterClass(flat_tile) && GetWaterClass(flat_tile) == WATER_CLASS_CANAL && IsTileOwner(flat_tile, _current_company))) {
2875  Company::Get(st->owner)->infrastructure.water++;
2876  }
2877  Company::Get(st->owner)->infrastructure.station += 2;
2878 
2879  MakeDock(tile, st->owner, st->index, direction, wc);
2880  UpdateStationDockingTiles(st);
2881 
2882  st->AfterStationTileSetChange(true, STATION_DOCK);
2883  }
2884 
2885  return cost;
2886 }
2887 
2888 void RemoveDockingTile(TileIndex t)
2889 {
2890  for (DiagDirection d = DIAGDIR_BEGIN; d != DIAGDIR_END; d++) {
2891  TileIndex tile = t + TileOffsByDiagDir(d);
2892  if (!IsValidTile(tile)) continue;
2893 
2894  if (IsTileType(tile, MP_STATION)) {
2895  Station *st = Station::GetByTile(tile);
2896  if (st != nullptr) UpdateStationDockingTiles(st);
2897  } else if (IsTileType(tile, MP_INDUSTRY)) {
2898  Station *neutral = Industry::GetByTile(tile)->neutral_station;
2899  if (neutral != nullptr) UpdateStationDockingTiles(neutral);
2900  }
2901  }
2902 }
2903 
2910 {
2911  assert(IsValidTile(tile));
2912 
2913  /* Clear and maybe re-set docking tile */
2914  for (DiagDirection d = DIAGDIR_BEGIN; d != DIAGDIR_END; d++) {
2915  TileIndex docking_tile = tile + TileOffsByDiagDir(d);
2916  if (!IsValidTile(docking_tile)) continue;
2917 
2918  if (IsPossibleDockingTile(docking_tile)) {
2919  SetDockingTile(docking_tile, false);
2920  CheckForDockingTile(docking_tile);
2921  }
2922  }
2923 }
2924 
2931 {
2932  assert(IsDockTile(t));
2933 
2934  StationGfx gfx = GetStationGfx(t);
2935  if (gfx < GFX_DOCK_BASE_WATER_PART) return t;
2936 
2937  for (DiagDirection d = DIAGDIR_BEGIN; d != DIAGDIR_END; d++) {
2938  TileIndex tile = t + TileOffsByDiagDir(d);
2939  if (!IsValidTile(tile)) continue;
2940  if (!IsDockTile(tile)) continue;
2941  if (GetStationGfx(tile) < GFX_DOCK_BASE_WATER_PART && tile + TileOffsByDiagDir(GetDockDirection(tile)) == t) return tile;
2942  }
2943 
2944  return INVALID_TILE;
2945 }
2946 
2954 {
2955  Station *st = Station::GetByTile(tile);
2956  CommandCost ret = CheckOwnership(st->owner);
2957  if (ret.Failed()) return ret;
2958 
2959  if (!IsDockTile(tile)) return CMD_ERROR;
2960 
2961  TileIndex tile1 = FindDockLandPart(tile);
2962  if (tile1 == INVALID_TILE) return CMD_ERROR;
2963  TileIndex tile2 = tile1 + TileOffsByDiagDir(GetDockDirection(tile1));
2964 
2965  ret = EnsureNoVehicleOnGround(tile1);
2966  if (ret.Succeeded()) ret = EnsureNoVehicleOnGround(tile2);
2967  if (ret.Failed()) return ret;
2968 
2969  if (flags & DC_EXEC) {
2970  DoClearSquare(tile1);
2971  MarkTileDirtyByTile(tile1);
2972  MakeWaterKeepingClass(tile2, st->owner);
2973 
2974  st->rect.AfterRemoveTile(st, tile1);
2975  st->rect.AfterRemoveTile(st, tile2);
2976 
2977  MakeShipStationAreaSmaller(st);
2978  if (st->ship_station.tile == INVALID_TILE) {
2979  st->ship_station.Clear();
2980  st->docking_station.Clear();
2981  st->facilities &= ~FACIL_DOCK;
2983  }
2984 
2985  Company::Get(st->owner)->infrastructure.station -= 2;
2986 
2987  st->AfterStationTileSetChange(false, STATION_DOCK);
2988 
2991 
2992  for (Ship *s : Ship::Iterate()) {
2993  /* Find all ships going to our dock. */
2994  if (s->current_order.GetDestination() != st->index) {
2995  continue;
2996  }
2997 
2998  /* Find ships that are marked as "loading" but are no longer on a
2999  * docking tile. Force them to leave the station (as they were loading
3000  * on the removed dock). */
3001  if (s->current_order.IsType(OT_LOADING) && !(IsDockingTile(s->tile) && IsShipDestinationTile(s->tile, st->index))) {
3002  s->LeaveStation();
3003  }
3004 
3005  /* If we no longer have a dock, mark the order as invalid and send
3006  * the ship to the next order (or, if there is none, make it
3007  * wander the world). */
3008  if (s->current_order.IsType(OT_GOTO_STATION) && !(st->facilities & FACIL_DOCK)) {
3009  s->SetDestTile(s->GetOrderStationLocation(st->index));
3010  }
3011  }
3012  }
3013 
3014  return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_STATION_DOCK]);
3015 }
3016 
3017 #include "table/station_land.h"
3018 
3026 {
3027  const auto &layouts = _station_display_datas[st];
3028  if (gfx >= layouts.size()) gfx &= 1;
3029  return layouts.data() + gfx;
3030 }
3031 
3041 bool SplitGroundSpriteForOverlay(const TileInfo *ti, SpriteID *ground, RailTrackOffset *overlay_offset)
3042 {
3043  bool snow_desert;
3044  switch (*ground) {
3045  case SPR_RAIL_TRACK_X:
3046  case SPR_MONO_TRACK_X:
3047  case SPR_MGLV_TRACK_X:
3048  snow_desert = false;
3049  *overlay_offset = RTO_X;
3050  break;
3051 
3052  case SPR_RAIL_TRACK_Y:
3053  case SPR_MONO_TRACK_Y:
3054  case SPR_MGLV_TRACK_Y:
3055  snow_desert = false;
3056  *overlay_offset = RTO_Y;
3057  break;
3058 
3059  case SPR_RAIL_TRACK_X_SNOW:
3060  case SPR_MONO_TRACK_X_SNOW:
3061  case SPR_MGLV_TRACK_X_SNOW:
3062  snow_desert = true;
3063  *overlay_offset = RTO_X;
3064  break;
3065 
3066  case SPR_RAIL_TRACK_Y_SNOW:
3067  case SPR_MONO_TRACK_Y_SNOW:
3068  case SPR_MGLV_TRACK_Y_SNOW:
3069  snow_desert = true;
3070  *overlay_offset = RTO_Y;
3071  break;
3072 
3073  default:
3074  return false;
3075  }
3076 
3077  if (ti != nullptr) {
3078  /* Decide snow/desert from tile */
3080  case LT_ARCTIC:
3081  snow_desert = (uint)ti->z > GetSnowLine() * TILE_HEIGHT;
3082  break;
3083 
3084  case LT_TROPIC:
3085  snow_desert = GetTropicZone(ti->tile) == TROPICZONE_DESERT;
3086  break;
3087 
3088  default:
3089  break;
3090  }
3091  }
3092 
3093  *ground = snow_desert ? SPR_FLAT_SNOW_DESERT_TILE : SPR_FLAT_GRASS_TILE;
3094  return true;
3095 }
3096 
3097 static void DrawTile_Station(TileInfo *ti)
3098 {
3099  const NewGRFSpriteLayout *layout = nullptr;
3100  DrawTileSprites tmp_rail_layout;
3101  const DrawTileSprites *t = nullptr;
3102  int32_t total_offset;
3103  const RailTypeInfo *rti = nullptr;
3104  uint32_t relocation = 0;
3105  uint32_t ground_relocation = 0;
3106  BaseStation *st = nullptr;
3107  const StationSpec *statspec = nullptr;
3108  uint tile_layout = 0;
3109 
3110  if (HasStationRail(ti->tile)) {
3111  rti = GetRailTypeInfo(GetRailType(ti->tile));
3112  total_offset = rti->GetRailtypeSpriteOffset();
3113 
3114  if (IsCustomStationSpecIndex(ti->tile)) {
3115  /* look for customization */
3116  st = BaseStation::GetByTile(ti->tile);
3117  statspec = st->speclist[GetCustomStationSpecIndex(ti->tile)].spec;
3118 
3119  if (statspec != nullptr) {
3120  tile_layout = GetStationGfx(ti->tile);
3121 
3123  uint16_t callback = GetStationCallback(CBID_STATION_DRAW_TILE_LAYOUT, 0, 0, statspec, st, ti->tile);
3124  if (callback != CALLBACK_FAILED) tile_layout = (callback & ~1) + GetRailStationAxis(ti->tile);
3125  }
3126 
3127  /* Ensure the chosen tile layout is valid for this custom station */
3128  if (!statspec->renderdata.empty()) {
3129  layout = &statspec->renderdata[tile_layout < statspec->renderdata.size() ? tile_layout : (uint)GetRailStationAxis(ti->tile)];
3130  if (!layout->NeedsPreprocessing()) {
3131  t = layout;
3132  layout = nullptr;
3133  }
3134  }
3135  }
3136  }
3137  } else {
3138  total_offset = 0;
3139  }
3140 
3141  StationGfx gfx = GetStationGfx(ti->tile);
3142  if (IsAirport(ti->tile)) {
3143  gfx = GetAirportGfx(ti->tile);
3144  if (gfx >= NEW_AIRPORTTILE_OFFSET) {
3145  const AirportTileSpec *ats = AirportTileSpec::Get(gfx);
3146  if (ats->grf_prop.spritegroup[0] != nullptr && DrawNewAirportTile(ti, Station::GetByTile(ti->tile), ats)) {
3147  return;
3148  }
3149  /* No sprite group (or no valid one) found, meaning no graphics associated.
3150  * Use the substitute one instead */
3151  assert(ats->grf_prop.subst_id != INVALID_AIRPORTTILE);
3152  gfx = ats->grf_prop.subst_id;
3153  }
3154  switch (gfx) {
3155  case APT_RADAR_GRASS_FENCE_SW:
3156  t = &_station_display_datas_airport_radar_grass_fence_sw[GetAnimationFrame(ti->tile)];
3157  break;
3158  case APT_GRASS_FENCE_NE_FLAG:
3159  t = &_station_display_datas_airport_flag_grass_fence_ne[GetAnimationFrame(ti->tile)];
3160  break;
3161  case APT_RADAR_FENCE_SW:
3162  t = &_station_display_datas_airport_radar_fence_sw[GetAnimationFrame(ti->tile)];
3163  break;
3164  case APT_RADAR_FENCE_NE:
3165  t = &_station_display_datas_airport_radar_fence_ne[GetAnimationFrame(ti->tile)];
3166  break;
3167  case APT_GRASS_FENCE_NE_FLAG_2:
3168  t = &_station_display_datas_airport_flag_grass_fence_ne_2[GetAnimationFrame(ti->tile)];
3169  break;
3170  }
3171  }
3172 
3173  Owner owner = GetTileOwner(ti->tile);
3174 
3175  PaletteID palette;
3176  if (Company::IsValidID(owner)) {
3177  palette = COMPANY_SPRITE_COLOUR(owner);
3178  } else {
3179  /* Some stations are not owner by a company, namely oil rigs */
3180  palette = PALETTE_TO_GREY;
3181  }
3182 
3183  if (layout == nullptr && (t == nullptr || t->seq == nullptr)) t = GetStationTileLayout(GetStationType(ti->tile), gfx);
3184 
3185  /* don't show foundation for docks */
3186  if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile)) {
3187  if (statspec != nullptr && HasBit(statspec->flags, SSF_CUSTOM_FOUNDATIONS)) {
3188  /* Station has custom foundations.
3189  * Check whether the foundation continues beyond the tile's upper sides. */
3190  uint edge_info = 0;
3191  auto [slope, z] = GetFoundationPixelSlope(ti->tile);
3192  if (!HasFoundationNW(ti->tile, slope, z)) SetBit(edge_info, 0);
3193  if (!HasFoundationNE(ti->tile, slope, z)) SetBit(edge_info, 1);
3194  SpriteID image = GetCustomStationFoundationRelocation(statspec, st, ti->tile, tile_layout, edge_info);
3195  if (image == 0) goto draw_default_foundation;
3196 
3197  if (HasBit(statspec->flags, SSF_EXTENDED_FOUNDATIONS)) {
3198  /* Station provides extended foundations. */
3199 
3200  static const uint8_t foundation_parts[] = {
3201  0, 0, 0, 0, // Invalid, Invalid, Invalid, SLOPE_SW
3202  0, 1, 2, 3, // Invalid, SLOPE_EW, SLOPE_SE, SLOPE_WSE
3203  0, 4, 5, 6, // Invalid, SLOPE_NW, SLOPE_NS, SLOPE_NWS
3204  7, 8, 9 // SLOPE_NE, SLOPE_ENW, SLOPE_SEN
3205  };
3206 
3207  AddSortableSpriteToDraw(image + foundation_parts[ti->tileh], PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
3208  } else {
3209  /* Draw simple foundations, built up from 8 possible foundation sprites. */
3210 
3211  /* Each set bit represents one of the eight composite sprites to be drawn.
3212  * 'Invalid' entries will not drawn but are included for completeness. */
3213  static const uint8_t composite_foundation_parts[] = {
3214  /* Invalid (00000000), Invalid (11010001), Invalid (11100100), SLOPE_SW (11100000) */
3215  0x00, 0xD1, 0xE4, 0xE0,
3216  /* Invalid (11001010), SLOPE_EW (11001001), SLOPE_SE (11000100), SLOPE_WSE (11000000) */
3217  0xCA, 0xC9, 0xC4, 0xC0,
3218  /* Invalid (11010010), SLOPE_NW (10010001), SLOPE_NS (11100100), SLOPE_NWS (10100000) */
3219  0xD2, 0x91, 0xE4, 0xA0,
3220  /* SLOPE_NE (01001010), SLOPE_ENW (00001001), SLOPE_SEN (01000100) */
3221  0x4A, 0x09, 0x44
3222  };
3223 
3224  uint8_t parts = composite_foundation_parts[ti->tileh];
3225 
3226  /* If foundations continue beyond the tile's upper sides then
3227  * mask out the last two pieces. */
3228  if (HasBit(edge_info, 0)) ClrBit(parts, 6);
3229  if (HasBit(edge_info, 1)) ClrBit(parts, 7);
3230 
3231  if (parts == 0) {
3232  /* We always have to draw at least one sprite to make sure there is a boundingbox and a sprite with the
3233  * correct offset for the childsprites.
3234  * So, draw the (completely empty) sprite of the default foundations. */
3235  goto draw_default_foundation;
3236  }
3237 
3239  for (int i = 0; i < 8; i++) {
3240  if (HasBit(parts, i)) {
3241  AddSortableSpriteToDraw(image + i, PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
3242  }
3243  }
3244  EndSpriteCombine();
3245  }
3246 
3247  OffsetGroundSprite(0, -8);
3249  } else {
3250 draw_default_foundation:
3252  }
3253  }
3254 
3255  bool draw_ground = false;
3256 
3257  if (IsBuoy(ti->tile)) {
3258  DrawWaterClassGround(ti);
3259  SpriteID sprite = GetCanalSprite(CF_BUOY, ti->tile);
3260  if (sprite != 0) total_offset = sprite - SPR_IMG_BUOY;
3261  } else if (IsDock(ti->tile) || (IsOilRig(ti->tile) && IsTileOnWater(ti->tile))) {
3262  if (ti->tileh == SLOPE_FLAT) {
3263  DrawWaterClassGround(ti);
3264  } else {
3265  assert(IsDock(ti->tile));
3266  TileIndex water_tile = ti->tile + TileOffsByDiagDir(GetDockDirection(ti->tile));
3267  WaterClass wc = HasTileWaterClass(water_tile) ? GetWaterClass(water_tile) : WATER_CLASS_INVALID;
3268  if (wc == WATER_CLASS_SEA) {
3269  DrawShoreTile(ti->tileh);
3270  } else {
3271  DrawClearLandTile(ti, 3);
3272  }
3273  }
3274  } else if (IsRoadWaypointTile(ti->tile)) {
3275  RoadBits bits = GetRoadStopDir(ti->tile) == DIAGDIR_NE ? ROAD_X : ROAD_Y;
3276  RoadType road_rt = GetRoadTypeRoad(ti->tile);
3277  RoadType tram_rt = GetRoadTypeTram(ti->tile);
3278  RoadBits road = (road_rt != INVALID_ROADTYPE) ? bits : ROAD_NONE;
3279  RoadBits tram = (tram_rt != INVALID_ROADTYPE) ? bits : ROAD_NONE;
3280  const RoadTypeInfo *road_rti = (road_rt != INVALID_ROADTYPE) ? GetRoadTypeInfo(road_rt) : nullptr;
3281  const RoadTypeInfo *tram_rti = (tram_rt != INVALID_ROADTYPE) ? GetRoadTypeInfo(tram_rt) : nullptr;
3282 
3283  if (ti->tileh != SLOPE_FLAT) {
3285  }
3286 
3287  DrawRoadGroundSprites(ti, road, tram, road_rti, tram_rti, GetRoadWaypointRoadside(ti->tile), IsRoadWaypointOnSnowOrDesert(ti->tile));
3288  } else {
3289  if (layout != nullptr) {
3290  /* Sprite layout which needs preprocessing */
3291  bool separate_ground = HasBit(statspec->flags, SSF_SEPARATE_GROUND);
3292  uint32_t var10_values = layout->PrepareLayout(total_offset, rti->fallback_railtype, 0, 0, separate_ground);
3293  for (uint8_t var10 : SetBitIterator(var10_values)) {
3294  uint32_t var10_relocation = GetCustomStationRelocation(statspec, st, ti->tile, var10);
3295  layout->ProcessRegisters(var10, var10_relocation, separate_ground);
3296  }
3297  tmp_rail_layout.seq = layout->GetLayout(&tmp_rail_layout.ground);
3298  t = &tmp_rail_layout;
3299  total_offset = 0;
3300  } else if (statspec != nullptr) {
3301  /* Simple sprite layout */
3302  ground_relocation = relocation = GetCustomStationRelocation(statspec, st, ti->tile, 0);
3303  if (HasBit(statspec->flags, SSF_SEPARATE_GROUND)) {
3304  ground_relocation = GetCustomStationRelocation(statspec, st, ti->tile, 1);
3305  }
3306  ground_relocation += rti->fallback_railtype;
3307  }
3308 
3309  draw_ground = true;
3310  }
3311 
3312  if (draw_ground && !IsAnyRoadStop(ti->tile)) {
3313  SpriteID image = t->ground.sprite;
3314  PaletteID pal = t->ground.pal;
3315  RailTrackOffset overlay_offset;
3316  if (rti != nullptr && rti->UsesOverlay() && SplitGroundSpriteForOverlay(ti, &image, &overlay_offset)) {
3317  SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
3318  DrawGroundSprite(image, PAL_NONE);
3319  DrawGroundSprite(ground + overlay_offset, PAL_NONE);
3320 
3321  if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationReservation(ti->tile)) {
3322  SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
3323  DrawGroundSprite(overlay + overlay_offset, PALETTE_CRASH);
3324  }
3325  } else {
3326  image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
3327  if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
3328  DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
3329 
3330  /* PBS debugging, draw reserved tracks darker */
3331  if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationRail(ti->tile) && HasStationReservation(ti->tile)) {
3333  }
3334  }
3335  }
3336 
3338 
3339  if (IsAnyRoadStop(ti->tile)) {
3340  RoadType road_rt = GetRoadTypeRoad(ti->tile);
3341  RoadType tram_rt = GetRoadTypeTram(ti->tile);
3342  const RoadTypeInfo *road_rti = road_rt == INVALID_ROADTYPE ? nullptr : GetRoadTypeInfo(road_rt);
3343  const RoadTypeInfo *tram_rti = tram_rt == INVALID_ROADTYPE ? nullptr : GetRoadTypeInfo(tram_rt);
3344 
3345  Axis axis = GetRoadStopDir(ti->tile) == DIAGDIR_NE ? AXIS_X : AXIS_Y;
3346  DiagDirection dir = GetRoadStopDir(ti->tile);
3347  StationType type = GetStationType(ti->tile);
3348 
3349  const RoadStopSpec *stopspec = GetRoadStopSpec(ti->tile);
3350  RoadStopDrawMode stop_draw_mode{};
3351  if (stopspec != nullptr) {
3352  stop_draw_mode = stopspec->draw_mode;
3353  int view = dir;
3354  if (IsDriveThroughStopTile(ti->tile)) view += 4;
3355  st = BaseStation::GetByTile(ti->tile);
3356  RoadStopResolverObject object(stopspec, st, ti->tile, INVALID_ROADTYPE, type, view);
3357  const SpriteGroup *group = object.Resolve();
3358  if (group != nullptr && group->type == SGT_TILELAYOUT) {
3359  if (HasBit(stopspec->flags, RSF_DRAW_MODE_REGISTER)) {
3360  stop_draw_mode = static_cast<RoadStopDrawMode>(GetRegister(0x100));
3361  }
3362  if (type == STATION_ROADWAYPOINT && (stop_draw_mode & ROADSTOP_DRAW_MODE_WAYP_GROUND)) {
3363  draw_ground = true;
3364  }
3365  t = ((const TileLayoutSpriteGroup *)group)->ProcessRegisters(nullptr);
3366  }
3367  }
3368 
3369  /* Draw ground sprite */
3370  if (draw_ground) {
3371  SpriteID image = t->ground.sprite;
3372  PaletteID pal = t->ground.pal;
3373  image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
3374  if (GB(image, 0, SPRITE_WIDTH) != 0) {
3375  if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
3376  DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
3377  }
3378  }
3379 
3380  if (IsDriveThroughStopTile(ti->tile)) {
3381  if (type != STATION_ROADWAYPOINT && (stopspec == nullptr || (stop_draw_mode & ROADSTOP_DRAW_MODE_OVERLAY) != 0)) {
3382  uint sprite_offset = axis == AXIS_X ? 1 : 0;
3383  DrawRoadOverlays(ti, PAL_NONE, road_rti, tram_rti, sprite_offset, sprite_offset);
3384  }
3385  } else {
3386  /* Non-drivethrough road stops are only valid for roads. */
3387  assert(road_rt != INVALID_ROADTYPE && tram_rt == INVALID_ROADTYPE);
3388 
3389  if ((stopspec == nullptr || (stop_draw_mode & ROADSTOP_DRAW_MODE_ROAD) != 0) && road_rti->UsesOverlay()) {
3390  SpriteID ground = GetCustomRoadSprite(road_rti, ti->tile, ROTSG_ROADSTOP);
3391  DrawGroundSprite(ground + dir, PAL_NONE);
3392  }
3393  }
3394 
3395  if (stopspec == nullptr || !HasBit(stopspec->flags, RSF_NO_CATENARY)) {
3396  /* Draw road, tram catenary */
3397  DrawRoadCatenary(ti);
3398  }
3399  }
3400 
3401  if (IsRailWaypoint(ti->tile)) {
3402  /* Don't offset the waypoint graphics; they're always the same. */
3403  total_offset = 0;
3404  }
3405 
3406  DrawRailTileSeq(ti, t, TO_BUILDINGS, total_offset, relocation, palette);
3407 }
3408 
3409 void StationPickerDrawSprite(int x, int y, StationType st, RailType railtype, RoadType roadtype, int image)
3410 {
3411  int32_t total_offset = 0;
3412  PaletteID pal = COMPANY_SPRITE_COLOUR(_local_company);
3413  const DrawTileSprites *t = GetStationTileLayout(st, image);
3414  const RailTypeInfo *railtype_info = nullptr;
3415 
3416  if (railtype != INVALID_RAILTYPE) {
3417  railtype_info = GetRailTypeInfo(railtype);
3418  total_offset = railtype_info->GetRailtypeSpriteOffset();
3419  }
3420 
3421  SpriteID img = t->ground.sprite;
3422  RailTrackOffset overlay_offset;
3423  if (railtype_info != nullptr && railtype_info->UsesOverlay() && SplitGroundSpriteForOverlay(nullptr, &img, &overlay_offset)) {
3424  SpriteID ground = GetCustomRailSprite(railtype_info, INVALID_TILE, RTSG_GROUND);
3425  DrawSprite(img, PAL_NONE, x, y);
3426  DrawSprite(ground + overlay_offset, PAL_NONE, x, y);
3427  } else {
3428  DrawSprite(img + total_offset, HasBit(img, PALETTE_MODIFIER_COLOUR) ? pal : PAL_NONE, x, y);
3429  }
3430 
3431  if (roadtype != INVALID_ROADTYPE) {
3432  const RoadTypeInfo *roadtype_info = GetRoadTypeInfo(roadtype);
3433  if (image >= 4) {
3434  /* Drive-through stop */
3435  uint sprite_offset = 5 - image;
3436 
3437  /* Road underlay takes precedence over tram */
3438  if (roadtype_info->UsesOverlay()) {
3439  SpriteID ground = GetCustomRoadSprite(roadtype_info, INVALID_TILE, ROTSG_GROUND);
3440  DrawSprite(ground + sprite_offset, PAL_NONE, x, y);
3441 
3442  SpriteID overlay = GetCustomRoadSprite(roadtype_info, INVALID_TILE, ROTSG_OVERLAY);
3443  if (overlay) DrawSprite(overlay + sprite_offset, PAL_NONE, x, y);
3444  } else if (RoadTypeIsTram(roadtype)) {
3445  DrawSprite(SPR_TRAMWAY_TRAM + sprite_offset, PAL_NONE, x, y);
3446  }
3447  } else {
3448  /* Bay stop */
3449  if (RoadTypeIsRoad(roadtype) && roadtype_info->UsesOverlay()) {
3450  SpriteID ground = GetCustomRoadSprite(roadtype_info, INVALID_TILE, ROTSG_ROADSTOP);
3451  DrawSprite(ground + image, PAL_NONE, x, y);
3452  }
3453  }
3454  }
3455 
3456  /* Default waypoint has no railtype specific sprites */
3457  DrawRailTileSeqInGUI(x, y, t, (st == STATION_WAYPOINT || st == STATION_ROADWAYPOINT) ? 0 : total_offset, 0, pal);
3458 }
3459 
3460 static int GetSlopePixelZ_Station(TileIndex tile, uint, uint, bool)
3461 {
3462  return GetTileMaxPixelZ(tile);
3463 }
3464 
3465 static Foundation GetFoundation_Station(TileIndex, Slope tileh)
3466 {
3467  return FlatteningFoundation(tileh);
3468 }
3469 
3470 static void FillTileDescRoadStop(TileIndex tile, TileDesc *td)
3471 {
3472  RoadType road_rt = GetRoadTypeRoad(tile);
3473  RoadType tram_rt = GetRoadTypeTram(tile);
3474  Owner road_owner = INVALID_OWNER;
3475  Owner tram_owner = INVALID_OWNER;
3476  if (road_rt != INVALID_ROADTYPE) {
3477  const RoadTypeInfo *rti = GetRoadTypeInfo(road_rt);
3478  td->roadtype = rti->strings.name;
3479  td->road_speed = rti->max_speed / 2;
3480  road_owner = GetRoadOwner(tile, RTT_ROAD);
3481  }
3482 
3483  if (tram_rt != INVALID_ROADTYPE) {
3484  const RoadTypeInfo *rti = GetRoadTypeInfo(tram_rt);
3485  td->tramtype = rti->strings.name;
3486  td->tram_speed = rti->max_speed / 2;
3487  tram_owner = GetRoadOwner(tile, RTT_TRAM);
3488  }
3489 
3490  if (IsDriveThroughStopTile(tile)) {
3491  /* Is there a mix of owners? */
3492  if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
3493  (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
3494  uint i = 1;
3495  if (road_owner != INVALID_OWNER) {
3496  td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
3497  td->owner[i] = road_owner;
3498  i++;
3499  }
3500  if (tram_owner != INVALID_OWNER) {
3501  td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
3502  td->owner[i] = tram_owner;
3503  }
3504  }
3505  }
3506 }
3507 
3508 void FillTileDescRailStation(TileIndex tile, TileDesc *td)
3509 {
3510  const StationSpec *spec = GetStationSpec(tile);
3511 
3512  if (spec != nullptr) {
3514  td->station_name = spec->name;
3515 
3516  if (spec->grf_prop.grffile != nullptr) {
3517  const GRFConfig *gc = GetGRFConfig(spec->grf_prop.grffile->grfid);
3518  td->grf = gc->GetName();
3519  }
3520  }
3521 
3522  const RailTypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
3523  td->rail_speed = rti->max_speed;
3524  td->railtype = rti->strings.name;
3525 }
3526 
3527 void FillTileDescAirport(TileIndex tile, TileDesc *td)
3528 {
3529  const AirportSpec *as = Station::GetByTile(tile)->airport.GetSpec();
3531  td->airport_name = as->name;
3532 
3533  const AirportTileSpec *ats = AirportTileSpec::GetByTile(tile);
3534  td->airport_tile_name = ats->name;
3535 
3536  if (as->grf_prop.grffile != nullptr) {
3537  const GRFConfig *gc = GetGRFConfig(as->grf_prop.grffile->grfid);
3538  td->grf = gc->GetName();
3539  } else if (ats->grf_prop.grffile != nullptr) {
3540  const GRFConfig *gc = GetGRFConfig(ats->grf_prop.grffile->grfid);
3541  td->grf = gc->GetName();
3542  }
3543 }
3544 
3545 static void GetTileDesc_Station(TileIndex tile, TileDesc *td)
3546 {
3547  td->owner[0] = GetTileOwner(tile);
3549 
3550  if (IsAnyRoadStop(tile)) FillTileDescRoadStop(tile, td);
3551  if (HasStationRail(tile)) FillTileDescRailStation(tile, td);
3552  if (IsAirport(tile)) FillTileDescAirport(tile, td);
3553 
3554  StringID str;
3555  switch (GetStationType(tile)) {
3556  default: NOT_REACHED();
3557  case STATION_RAIL: str = STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION; break;
3558  case STATION_AIRPORT:
3559  str = (IsHangar(tile) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR : STR_LAI_STATION_DESCRIPTION_AIRPORT);
3560  break;
3561  case STATION_TRUCK: str = STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA; break;
3562  case STATION_BUS: str = STR_LAI_STATION_DESCRIPTION_BUS_STATION; break;
3563  case STATION_OILRIG: {
3564  const Industry *i = Station::GetByTile(tile)->industry;
3565  const IndustrySpec *is = GetIndustrySpec(i->type);
3566  td->owner[0] = i->owner;
3567  str = is->name;
3568  if (is->grf_prop.grffile != nullptr) td->grf = GetGRFConfig(is->grf_prop.grffile->grfid)->GetName();
3569  break;
3570  }
3571  case STATION_DOCK: str = STR_LAI_STATION_DESCRIPTION_SHIP_DOCK; break;
3572  case STATION_BUOY: str = STR_LAI_STATION_DESCRIPTION_BUOY; break;
3573  case STATION_WAYPOINT: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
3574  case STATION_ROADWAYPOINT: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
3575  }
3576  td->str = str;
3577 }
3578 
3579 
3580 static TrackStatus GetTileTrackStatus_Station(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
3581 {
3582  TrackBits trackbits = TRACK_BIT_NONE;
3583 
3584  switch (mode) {
3585  case TRANSPORT_RAIL:
3586  if (HasStationRail(tile) && !IsStationTileBlocked(tile)) {
3587  trackbits = TrackToTrackBits(GetRailStationTrack(tile));
3588  }
3589  break;
3590 
3591  case TRANSPORT_WATER:
3592  /* buoy is coded as a station, it is always on open water */
3593  if (IsBuoy(tile)) {
3594  trackbits = TRACK_BIT_ALL;
3595  /* remove tracks that connect NE map edge */
3596  if (TileX(tile) == 0) trackbits &= ~(TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT);
3597  /* remove tracks that connect NW map edge */
3598  if (TileY(tile) == 0) trackbits &= ~(TRACK_BIT_Y | TRACK_BIT_LEFT | TRACK_BIT_UPPER);
3599  }
3600  break;
3601 
3602  case TRANSPORT_ROAD:
3603  if (IsAnyRoadStop(tile)) {
3604  RoadTramType rtt = (RoadTramType)sub_mode;
3605  if (!HasTileRoadType(tile, rtt)) break;
3606 
3607  DiagDirection dir = GetRoadStopDir(tile);
3608  Axis axis = DiagDirToAxis(dir);
3609 
3610  if (side != INVALID_DIAGDIR) {
3611  if (axis != DiagDirToAxis(side) || (IsBayRoadStopTile(tile) && dir != side)) break;
3612  }
3613 
3614  trackbits = AxisToTrackBits(axis);
3615  }
3616  break;
3617 
3618  default:
3619  break;
3620  }
3621 
3623 }
3624 
3625 
3626 static void TileLoop_Station(TileIndex tile)
3627 {
3628  /* FIXME -- GetTileTrackStatus_Station -> animated stationtiles
3629  * hardcoded.....not good */
3630  switch (GetStationType(tile)) {
3631  case STATION_AIRPORT:
3632  AirportTileAnimationTrigger(Station::GetByTile(tile), tile, AAT_TILELOOP);
3633  break;
3634 
3635  case STATION_DOCK:
3636  if (!IsTileFlat(tile)) break; // only handle water part
3637  [[fallthrough]];
3638 
3639  case STATION_OILRIG: //(station part)
3640  case STATION_BUOY:
3641  TileLoop_Water(tile);
3642  break;
3643 
3644  case STATION_ROADWAYPOINT: {
3646  case LT_ARCTIC:
3647  if (IsRoadWaypointOnSnowOrDesert(tile) != (GetTileZ(tile) > GetSnowLine())) {
3649  MarkTileDirtyByTile(tile);
3650  }
3651  break;
3652 
3653  case LT_TROPIC:
3656  MarkTileDirtyByTile(tile);
3657  }
3658  break;
3659 
3660  default: break;
3661  }
3662 
3663  HouseZonesBits new_zone = HZB_TOWN_EDGE;
3664  const Town *t = ClosestTownFromTile(tile, UINT_MAX);
3665  if (t != nullptr) {
3666  new_zone = GetTownRadiusGroup(t, tile);
3667  }
3668 
3669  /* Adjust road ground type depending on 'new_zone' */
3670  Roadside new_rs = new_zone > HZB_TOWN_EDGE ? ROADSIDE_PAVED : ROADSIDE_GRASS;
3671  Roadside cur_rs = GetRoadWaypointRoadside(tile);
3672 
3673  if (new_rs != cur_rs) {
3674  SetRoadWaypointRoadside(tile, cur_rs == ROADSIDE_BARREN ? new_rs : ROADSIDE_BARREN);
3675  MarkTileDirtyByTile(tile);
3676  }
3677  break;
3678  }
3679 
3680  default: break;
3681  }
3682 }
3683 
3684 
3685 static void AnimateTile_Station(TileIndex tile)
3686 {
3687  if (HasStationRail(tile)) {
3688  AnimateStationTile(tile);
3689  return;
3690  }
3691 
3692  if (IsAirport(tile)) {
3693  AnimateAirportTile(tile);
3694  return;
3695  }
3696 
3697  if (IsAnyRoadStopTile(tile)) {
3698  AnimateRoadStopTile(tile);
3699  return;
3700  }
3701 }
3702 
3703 
3704 static bool ClickTile_Station(TileIndex tile)
3705 {
3706  const BaseStation *bst = BaseStation::GetByTile(tile);
3707 
3708  if (bst->facilities & FACIL_WAYPOINT) {
3710  } else if (IsHangar(tile)) {
3711  const Station *st = Station::From(bst);
3713  } else {
3715  }
3716  return true;
3717 }
3718 
3719 static VehicleEnterTileStatus VehicleEnter_Station(Vehicle *v, TileIndex tile, int x, int y)
3720 {
3721  if (v->type == VEH_TRAIN) {
3722  StationID station_id = GetStationIndex(tile);
3723  if (!v->current_order.ShouldStopAtStation(v, station_id)) return VETSB_CONTINUE;
3724  if (!IsRailStation(tile) || !v->IsFrontEngine()) return VETSB_CONTINUE;
3725 
3726  int station_ahead;
3727  int station_length;
3728  int stop = GetTrainStopLocation(station_id, tile, Train::From(v), &station_ahead, &station_length);
3729 
3730  /* Stop whenever that amount of station ahead + the distance from the
3731  * begin of the platform to the stop location is longer than the length
3732  * of the platform. Station ahead 'includes' the current tile where the
3733  * vehicle is on, so we need to subtract that. */
3734  if (stop + station_ahead - (int)TILE_SIZE >= station_length) return VETSB_CONTINUE;
3735 
3737 
3738  x &= 0xF;
3739  y &= 0xF;
3740 
3741  if (DiagDirToAxis(dir) != AXIS_X) Swap(x, y);
3742  if (y == TILE_SIZE / 2) {
3743  if (dir != DIAGDIR_SE && dir != DIAGDIR_SW) x = TILE_SIZE - 1 - x;
3744  stop &= TILE_SIZE - 1;
3745 
3746  if (x == stop) {
3747  return VETSB_ENTERED_STATION | (VehicleEnterTileStatus)(station_id << VETS_STATION_ID_OFFSET); // enter station
3748  } else if (x < stop) {
3750  uint16_t spd = std::max(0, (stop - x) * 20 - 15);
3751  if (spd < v->cur_speed) v->cur_speed = spd;
3752  }
3753  }
3754  } else if (v->type == VEH_ROAD) {
3755  RoadVehicle *rv = RoadVehicle::From(v);
3756  if (rv->state < RVSB_IN_ROAD_STOP && !IsReversingRoadTrackdir((Trackdir)rv->state) && rv->frame == 0) {
3757  if (IsStationRoadStop(tile) && rv->IsFrontEngine()) {
3758  /* Attempt to allocate a parking bay in a road stop */
3760  }
3761  }
3762  }
3763 
3764  return VETSB_CONTINUE;
3765 }
3766 
3772 {
3773  /* Collect cargoes accepted since the last big tick. */
3774  CargoTypes cargoes = 0;
3775  for (CargoID cid = 0; cid < NUM_CARGO; cid++) {
3776  if (HasBit(st->goods[cid].status, GoodsEntry::GES_ACCEPTED_BIGTICK)) SetBit(cargoes, cid);
3777  }
3778 
3779  /* Anything to do? */
3780  if (cargoes == 0) return;
3781 
3782  /* Loop over all houses in the catchment. */
3784  for (TileIndex tile = it; tile != INVALID_TILE; tile = ++it) {
3785  if (IsTileType(tile, MP_HOUSE)) {
3786  WatchedCargoCallback(tile, cargoes);
3787  }
3788  }
3789 }
3790 
3798 {
3799  if (!st->IsInUse()) {
3800  if (++st->delete_ctr >= 8) delete st;
3801  return false;
3802  }
3803 
3804  if (Station::IsExpected(st)) {
3806 
3807  for (GoodsEntry &ge : Station::From(st)->goods) {
3809  }
3810  }
3811 
3812 
3813  if ((st->facilities & FACIL_WAYPOINT) == 0) UpdateStationAcceptance(Station::From(st), true);
3814 
3815  return true;
3816 }
3817 
3818 static inline void byte_inc_sat(uint8_t *p)
3819 {
3820  uint8_t b = *p + 1;
3821  if (b != 0) *p = b;
3822 }
3823 
3830 static void TruncateCargo(const CargoSpec *cs, GoodsEntry *ge, uint amount = UINT_MAX)
3831 {
3832  /* If truncating also punish the source stations' ratings to
3833  * decrease the flow of incoming cargo. */
3834 
3835  StationCargoAmountMap waiting_per_source;
3836  ge->cargo.Truncate(amount, &waiting_per_source);
3837  for (StationCargoAmountMap::iterator i(waiting_per_source.begin()); i != waiting_per_source.end(); ++i) {
3838  Station *source_station = Station::GetIfValid(i->first);
3839  if (source_station == nullptr) continue;
3840 
3841  GoodsEntry &source_ge = source_station->goods[cs->Index()];
3842  source_ge.max_waiting_cargo = std::max(source_ge.max_waiting_cargo, i->second);
3843  }
3844 }
3845 
3846 static void UpdateStationRating(Station *st)
3847 {
3848  bool waiting_changed = false;
3849 
3850  byte_inc_sat(&st->time_since_load);
3851  byte_inc_sat(&st->time_since_unload);
3852 
3853  for (const CargoSpec *cs : CargoSpec::Iterate()) {
3854  GoodsEntry *ge = &st->goods[cs->Index()];
3855  /* Slowly increase the rating back to its original level in the case we
3856  * didn't deliver cargo yet to this station. This happens when a bribe
3857  * failed while you didn't moved that cargo yet to a station. */
3858  if (!ge->HasRating() && ge->rating < INITIAL_STATION_RATING) {
3859  ge->rating++;
3860  }
3861 
3862  /* Only change the rating if we are moving this cargo */
3863  if (ge->HasRating()) {
3864  byte_inc_sat(&ge->time_since_pickup);
3865  if (ge->time_since_pickup == 255 && _settings_game.order.selectgoods) {
3867  ge->last_speed = 0;
3868  TruncateCargo(cs, ge);
3869  waiting_changed = true;
3870  continue;
3871  }
3872 
3873  bool skip = false;
3874  int rating = 0;
3875  uint waiting = ge->cargo.AvailableCount();
3876 
3877  /* num_dests is at least 1 if there is any cargo as
3878  * INVALID_STATION is also a destination.
3879  */
3880  uint num_dests = (uint)ge->cargo.Packets()->MapSize();
3881 
3882  /* Average amount of cargo per next hop, but prefer solitary stations
3883  * with only one or two next hops. They are allowed to have more
3884  * cargo waiting per next hop.
3885  * With manual cargo distribution waiting_avg = waiting / 2 as then
3886  * INVALID_STATION is the only destination.
3887  */
3888  uint waiting_avg = waiting / (num_dests + 1);
3889 
3891  ge->rating = rating = MAX_STATION_RATING;
3892  skip = true;
3893  } else if (HasBit(cs->callback_mask, CBM_CARGO_STATION_RATING_CALC)) {
3894  /* Perform custom station rating. If it succeeds the speed, days in transit and
3895  * waiting cargo ratings must not be executed. */
3896 
3897  /* NewGRFs expect last speed to be 0xFF when no vehicle has arrived yet. */
3898  uint last_speed = ge->HasVehicleEverTriedLoading() ? ge->last_speed : 0xFF;
3899 
3900  uint32_t var18 = ClampTo<uint8_t>(ge->time_since_pickup)
3901  | (ClampTo<uint16_t>(ge->max_waiting_cargo) << 8)
3902  | (ClampTo<uint8_t>(last_speed) << 24);
3903  /* Convert to the 'old' vehicle types */
3904  uint32_t var10 = (st->last_vehicle_type == VEH_INVALID) ? 0x0 : (st->last_vehicle_type + 0x10);
3905  uint16_t callback = GetCargoCallback(CBID_CARGO_STATION_RATING_CALC, var10, var18, cs);
3906  if (callback != CALLBACK_FAILED) {
3907  skip = true;
3908  rating = GB(callback, 0, 14);
3909 
3910  /* Simulate a 15 bit signed value */
3911  if (HasBit(callback, 14)) rating -= 0x4000;
3912  }
3913  }
3914 
3915  if (!skip) {
3916  int b = ge->last_speed - 85;
3917  if (b >= 0) rating += b >> 2;
3918 
3919  uint8_t waittime = ge->time_since_pickup;
3920  if (st->last_vehicle_type == VEH_SHIP) waittime >>= 2;
3921  if (waittime <= 21) rating += 25;
3922  if (waittime <= 12) rating += 25;
3923  if (waittime <= 6) rating += 45;
3924  if (waittime <= 3) rating += 35;
3925 
3926  rating -= 90;
3927  if (ge->max_waiting_cargo <= 1500) rating += 55;
3928  if (ge->max_waiting_cargo <= 1000) rating += 35;
3929  if (ge->max_waiting_cargo <= 600) rating += 10;
3930  if (ge->max_waiting_cargo <= 300) rating += 20;
3931  if (ge->max_waiting_cargo <= 100) rating += 10;
3932  }
3933 
3934  if (Company::IsValidID(st->owner) && HasBit(st->town->statues, st->owner)) rating += 26;
3935 
3936  uint8_t age = ge->last_age;
3937  if (age < 3) rating += 10;
3938  if (age < 2) rating += 10;
3939  if (age < 1) rating += 13;
3940 
3941  {
3942  int or_ = ge->rating; // old rating
3943 
3944  /* only modify rating in steps of -2, -1, 0, 1 or 2 */
3945  ge->rating = rating = or_ + Clamp(ClampTo<uint8_t>(rating) - or_, -2, 2);
3946 
3947  /* if rating is <= 64 and more than 100 items waiting on average per destination,
3948  * remove some random amount of goods from the station */
3949  if (rating <= 64 && waiting_avg >= 100) {
3950  int dec = Random() & 0x1F;
3951  if (waiting_avg < 200) dec &= 7;
3952  waiting -= (dec + 1) * num_dests;
3953  waiting_changed = true;
3954  }
3955 
3956  /* if rating is <= 127 and there are any items waiting, maybe remove some goods. */
3957  if (rating <= 127 && waiting != 0) {
3958  uint32_t r = Random();
3959  if (rating <= (int)GB(r, 0, 7)) {
3960  /* Need to have int, otherwise it will just overflow etc. */
3961  waiting = std::max((int)waiting - (int)((GB(r, 8, 2) - 1) * num_dests), 0);
3962  waiting_changed = true;
3963  }
3964  }
3965 
3966  /* At some point we really must cap the cargo. Previously this
3967  * was a strict 4095, but now we'll have a less strict, but
3968  * increasingly aggressive truncation of the amount of cargo. */
3969  static const uint WAITING_CARGO_THRESHOLD = 1 << 12;
3970  static const uint WAITING_CARGO_CUT_FACTOR = 1 << 6;
3971  static const uint MAX_WAITING_CARGO = 1 << 15;
3972 
3973  if (waiting > WAITING_CARGO_THRESHOLD) {
3974  uint difference = waiting - WAITING_CARGO_THRESHOLD;
3975  waiting -= (difference / WAITING_CARGO_CUT_FACTOR);
3976 
3977  waiting = std::min(waiting, MAX_WAITING_CARGO);
3978  waiting_changed = true;
3979  }
3980 
3981  /* We can't truncate cargo that's already reserved for loading.
3982  * Thus StoredCount() here. */
3983  if (waiting_changed && waiting < ge->cargo.AvailableCount()) {
3984  /* Feed back the exact own waiting cargo at this station for the
3985  * next rating calculation. */
3986  ge->max_waiting_cargo = 0;
3987 
3988  TruncateCargo(cs, ge, ge->cargo.AvailableCount() - waiting);
3989  } else {
3990  /* If the average number per next hop is low, be more forgiving. */
3991  ge->max_waiting_cargo = waiting_avg;
3992  }
3993  }
3994  }
3995  }
3996 
3997  StationID index = st->index;
3998  if (waiting_changed) {
3999  SetWindowDirty(WC_STATION_VIEW, index); // update whole window
4000  } else {
4001  SetWindowWidgetDirty(WC_STATION_VIEW, index, WID_SV_ACCEPT_RATING_LIST); // update only ratings list
4002  }
4003 }
4004 
4013 void RerouteCargo(Station *st, CargoID c, StationID avoid, StationID avoid2)
4014 {
4015  GoodsEntry &ge = st->goods[c];
4016 
4017  /* Reroute cargo in station. */
4018  ge.cargo.Reroute(UINT_MAX, &ge.cargo, avoid, avoid2, &ge);
4019 
4020  /* Reroute cargo staged to be transferred. */
4021  for (Vehicle *v : st->loading_vehicles) {
4022  for (Vehicle *u = v; u != nullptr; u = u->Next()) {
4023  if (u->cargo_type != c) continue;
4024  u->cargo.Reroute(UINT_MAX, &u->cargo, avoid, avoid2, &ge);
4025  }
4026  }
4027 }
4028 
4038 {
4039  for (CargoID c = 0; c < NUM_CARGO; ++c) {
4040  const bool auto_distributed = (_settings_game.linkgraph.GetDistributionType(c) != DT_MANUAL);
4041  GoodsEntry &ge = from->goods[c];
4043  if (lg == nullptr) continue;
4044  std::vector<NodeID> to_remove{};
4045  for (Edge &edge : (*lg)[ge.node].edges) {
4046  Station *to = Station::Get((*lg)[edge.dest_node].station);
4047  assert(to->goods[c].node == edge.dest_node);
4048  assert(TimerGameEconomy::date >= edge.LastUpdate());
4049  auto timeout = TimerGameEconomy::Date(LinkGraph::MIN_TIMEOUT_DISTANCE + (DistanceManhattan(from->xy, to->xy) >> 3));
4050  if (TimerGameEconomy::date - edge.LastUpdate() > timeout) {
4051  bool updated = false;
4052 
4053  if (auto_distributed) {
4054  /* Have all vehicles refresh their next hops before deciding to
4055  * remove the node. */
4056  std::vector<Vehicle *> vehicles;
4057  for (OrderList *l : OrderList::Iterate()) {
4058  bool found_from = false;
4059  bool found_to = false;
4060  for (Order *order = l->GetFirstOrder(); order != nullptr; order = order->next) {
4061  if (!order->IsType(OT_GOTO_STATION) && !order->IsType(OT_IMPLICIT)) continue;
4062  if (order->GetDestination() == from->index) {
4063  found_from = true;
4064  if (found_to) break;
4065  } else if (order->GetDestination() == to->index) {
4066  found_to = true;
4067  if (found_from) break;
4068  }
4069  }
4070  if (!found_to || !found_from) continue;
4071  vehicles.push_back(l->GetFirstSharedVehicle());
4072  }
4073 
4074  auto iter = vehicles.begin();
4075  while (iter != vehicles.end()) {
4076  Vehicle *v = *iter;
4077  /* Do not refresh links of vehicles that have been stopped in depot for a long time. */
4079  LinkRefresher::Run(v, false); // Don't allow merging. Otherwise lg might get deleted.
4080  }
4081  if (edge.LastUpdate() == TimerGameEconomy::date) {
4082  updated = true;
4083  break;
4084  }
4085 
4086  Vehicle *next_shared = v->NextShared();
4087  if (next_shared) {
4088  *iter = next_shared;
4089  ++iter;
4090  } else {
4091  iter = vehicles.erase(iter);
4092  }
4093 
4094  if (iter == vehicles.end()) iter = vehicles.begin();
4095  }
4096  }
4097 
4098  if (!updated) {
4099  /* If it's still considered dead remove it. */
4100  to_remove.emplace_back(to->goods[c].node);
4101  ge.flows.DeleteFlows(to->index);
4102  RerouteCargo(from, c, to->index, from->index);
4103  }
4104  } else if (edge.last_unrestricted_update != EconomyTime::INVALID_DATE && TimerGameEconomy::date - edge.last_unrestricted_update > timeout) {
4105  edge.Restrict();
4106  ge.flows.RestrictFlows(to->index);
4107  RerouteCargo(from, c, to->index, from->index);
4108  } else if (edge.last_restricted_update != EconomyTime::INVALID_DATE && TimerGameEconomy::date - edge.last_restricted_update > timeout) {
4109  edge.Release();
4110  }
4111  }
4112  /* Remove dead edges. */
4113  for (NodeID r : to_remove) (*lg)[ge.node].RemoveEdge(r);
4114 
4115  assert(TimerGameEconomy::date >= lg->LastCompression());
4117  lg->Compress();
4118  }
4119  }
4120 }
4121 
4131 void IncreaseStats(Station *st, CargoID cargo, StationID next_station_id, uint capacity, uint usage, uint32_t time, EdgeUpdateMode mode)
4132 {
4133  GoodsEntry &ge1 = st->goods[cargo];
4134  Station *st2 = Station::Get(next_station_id);
4135  GoodsEntry &ge2 = st2->goods[cargo];
4136  LinkGraph *lg = nullptr;
4137  if (ge1.link_graph == INVALID_LINK_GRAPH) {
4138  if (ge2.link_graph == INVALID_LINK_GRAPH) {
4140  lg = new LinkGraph(cargo);
4142  ge2.link_graph = lg->index;
4143  ge2.node = lg->AddNode(st2);
4144  } else {
4145  Debug(misc, 0, "Can't allocate link graph");
4146  }
4147  } else {
4148  lg = LinkGraph::Get(ge2.link_graph);
4149  }
4150  if (lg) {
4151  ge1.link_graph = lg->index;
4152  ge1.node = lg->AddNode(st);
4153  }
4154  } else if (ge2.link_graph == INVALID_LINK_GRAPH) {
4155  lg = LinkGraph::Get(ge1.link_graph);
4156  ge2.link_graph = lg->index;
4157  ge2.node = lg->AddNode(st2);
4158  } else {
4159  lg = LinkGraph::Get(ge1.link_graph);
4160  if (ge1.link_graph != ge2.link_graph) {
4161  LinkGraph *lg2 = LinkGraph::Get(ge2.link_graph);
4162  if (lg->Size() < lg2->Size()) {
4164  lg2->Merge(lg); // Updates GoodsEntries of lg
4165  lg = lg2;
4166  } else {
4168  lg->Merge(lg2); // Updates GoodsEntries of lg2
4169  }
4170  }
4171  }
4172  if (lg != nullptr) {
4173  (*lg)[ge1.node].UpdateEdge(ge2.node, capacity, usage, time, mode);
4174  }
4175 }
4176 
4183 void IncreaseStats(Station *st, const Vehicle *front, StationID next_station_id, uint32_t time)
4184 {
4185  for (const Vehicle *v = front; v != nullptr; v = v->Next()) {
4186  if (v->refit_cap > 0) {
4187  /* The cargo count can indeed be higher than the refit_cap if
4188  * wagons have been auto-replaced and subsequently auto-
4189  * refitted to a higher capacity. The cargo gets redistributed
4190  * among the wagons in that case.
4191  * As usage is not such an important figure anyway we just
4192  * ignore the additional cargo then.*/
4193  IncreaseStats(st, v->cargo_type, next_station_id, v->refit_cap,
4194  std::min<uint>(v->refit_cap, v->cargo.StoredCount()), time, EUM_INCREASE);
4195  }
4196  }
4197 }
4198 
4199 /* called for every station each tick */
4200 static void StationHandleSmallTick(BaseStation *st)
4201 {
4202  if ((st->facilities & FACIL_WAYPOINT) != 0 || !st->IsInUse()) return;
4203 
4204  uint8_t b = st->delete_ctr + 1;
4205  if (b >= Ticks::STATION_RATING_TICKS) b = 0;
4206  st->delete_ctr = b;
4207 
4208  if (b == 0) UpdateStationRating(Station::From(st));
4209 }
4210 
4211 void OnTick_Station()
4212 {
4213  if (_game_mode == GM_EDITOR) return;
4214 
4215  for (BaseStation *st : BaseStation::Iterate()) {
4216  StationHandleSmallTick(st);
4217 
4218  /* Clean up the link graph about once a week. */
4221  };
4222 
4223  /* Spread out big-tick over STATION_ACCEPTANCE_TICKS ticks. */
4225  /* Stop processing this station if it was deleted */
4226  if (!StationHandleBigTick(st)) continue;
4227  }
4228 
4229  /* Spread out station animation over STATION_ACCEPTANCE_TICKS ticks. */
4231  TriggerStationAnimation(st, st->xy, SAT_250_TICKS);
4232  TriggerRoadStopAnimation(st, st->xy, SAT_250_TICKS);
4233  if (Station::IsExpected(st)) AirportAnimationTrigger(Station::From(st), AAT_STATION_250_TICKS);
4234  }
4235  }
4236 }
4237 
4239 static IntervalTimer<TimerGameEconomy> _economy_stations_monthly({TimerGameEconomy::MONTH, TimerGameEconomy::Priority::STATION}, [](auto)
4240 {
4241  for (Station *st : Station::Iterate()) {
4242  for (GoodsEntry &ge : st->goods) {
4245  }
4246  }
4247 });
4248 
4249 void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
4250 {
4251  ForAllStationsRadius(tile, radius, [&](Station *st) {
4252  if (st->owner == owner && DistanceManhattan(tile, st->xy) <= radius) {
4253  for (GoodsEntry &ge : st->goods) {
4254  if (ge.status != 0) {
4255  ge.rating = ClampTo<uint8_t>(ge.rating + amount);
4256  }
4257  }
4258  }
4259  });
4260 }
4261 
4262 static uint UpdateStationWaiting(Station *st, CargoID type, uint amount, SourceType source_type, SourceID source_id)
4263 {
4264  /* We can't allocate a CargoPacket? Then don't do anything
4265  * at all; i.e. just discard the incoming cargo. */
4266  if (!CargoPacket::CanAllocateItem()) return 0;
4267 
4268  GoodsEntry &ge = st->goods[type];
4269  amount += ge.amount_fract;
4270  ge.amount_fract = GB(amount, 0, 8);
4271 
4272  amount >>= 8;
4273  /* No new "real" cargo item yet. */
4274  if (amount == 0) return 0;
4275 
4276  StationID next = ge.GetVia(st->index);
4277  ge.cargo.Append(new CargoPacket(st->index, amount, source_type, source_id), next);
4278  LinkGraph *lg = nullptr;
4279  if (ge.link_graph == INVALID_LINK_GRAPH) {
4281  lg = new LinkGraph(type);
4283  ge.link_graph = lg->index;
4284  ge.node = lg->AddNode(st);
4285  } else {
4286  Debug(misc, 0, "Can't allocate link graph");
4287  }
4288  } else {
4289  lg = LinkGraph::Get(ge.link_graph);
4290  }
4291  if (lg != nullptr) (*lg)[ge.node].UpdateSupply(amount);
4292 
4293  if (!ge.HasRating()) {
4296  }
4297 
4299  TriggerStationAnimation(st, st->xy, SAT_NEW_CARGO, type);
4300  AirportAnimationTrigger(st, AAT_STATION_NEW_CARGO, type);
4302  TriggerRoadStopAnimation(st, st->xy, SAT_NEW_CARGO, type);
4303 
4304 
4306  st->MarkTilesDirty(true);
4307  return amount;
4308 }
4309 
4310 static bool IsUniqueStationName(const std::string &name)
4311 {
4312  for (const Station *st : Station::Iterate()) {
4313  if (!st->name.empty() && st->name == name) return false;
4314  }
4315 
4316  return true;
4317 }
4318 
4326 CommandCost CmdRenameStation(DoCommandFlag flags, StationID station_id, const std::string &text)
4327 {
4328  Station *st = Station::GetIfValid(station_id);
4329  if (st == nullptr) return CMD_ERROR;
4330 
4331  CommandCost ret = CheckOwnership(st->owner);
4332  if (ret.Failed()) return ret;
4333 
4334  bool reset = text.empty();
4335 
4336  if (!reset) {
4338  if (!IsUniqueStationName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
4339  }
4340 
4341  if (flags & DC_EXEC) {
4342  st->cached_name.clear();
4343  if (reset) {
4344  st->name.clear();
4345  } else {
4346  st->name = text;
4347  }
4348 
4349  st->UpdateVirtCoord();
4351  }
4352 
4353  return CommandCost();
4354 }
4355 
4356 static void AddNearbyStationsByCatchment(TileIndex tile, StationList *stations, StationList &nearby)
4357 {
4358  for (Station *st : nearby) {
4359  if (st->TileIsInCatchment(tile)) stations->insert(st);
4360  }
4361 }
4362 
4368 {
4369  if (this->tile != INVALID_TILE) {
4370  if (IsTileType(this->tile, MP_HOUSE)) {
4371  /* Town nearby stations need to be filtered per tile. */
4372  assert(this->w == 1 && this->h == 1);
4373  AddNearbyStationsByCatchment(this->tile, &this->stations, Town::GetByTile(this->tile)->stations_near);
4374  } else {
4375  ForAllStationsAroundTiles(*this, [this](Station *st, TileIndex) {
4376  this->stations.insert(st);
4377  return true;
4378  });
4379  }
4380  this->tile = INVALID_TILE;
4381  }
4382  return &this->stations;
4383 }
4384 
4385 
4386 static bool CanMoveGoodsToStation(const Station *st, CargoID type)
4387 {
4388  /* Is the station reserved exclusively for somebody else? */
4389  if (st->owner != OWNER_NONE && st->town->exclusive_counter > 0 && st->town->exclusivity != st->owner) return false;
4390 
4391  /* Lowest possible rating, better not to give cargo anymore. */
4392  if (st->goods[type].rating == 0) return false;
4393 
4394  /* Selectively servicing stations, and not this one. */
4395  if (_settings_game.order.selectgoods && !st->goods[type].HasVehicleEverTriedLoading()) return false;
4396 
4397  if (IsCargoInClass(type, CC_PASSENGERS)) {
4398  /* Passengers are never served by just a truck stop. */
4399  if (st->facilities == FACIL_TRUCK_STOP) return false;
4400  } else {
4401  /* Non-passengers are never served by just a bus stop. */
4402  if (st->facilities == FACIL_BUS_STOP) return false;
4403  }
4404  return true;
4405 }
4406 
4407 uint MoveGoodsToStation(CargoID type, uint amount, SourceType source_type, SourceID source_id, const StationList *all_stations, Owner exclusivity)
4408 {
4409  /* Return if nothing to do. Also the rounding below fails for 0. */
4410  if (all_stations->empty()) return 0;
4411  if (amount == 0) return 0;
4412 
4413  Station *first_station = nullptr;
4414  typedef std::pair<Station *, uint> StationInfo;
4415  std::vector<StationInfo> used_stations;
4416 
4417  for (Station *st : *all_stations) {
4418  if (exclusivity != INVALID_OWNER && exclusivity != st->owner) continue;
4419  if (!CanMoveGoodsToStation(st, type)) continue;
4420 
4421  /* Avoid allocating a vector if there is only one station to significantly
4422  * improve performance in this common case. */
4423  if (first_station == nullptr) {
4424  first_station = st;
4425  continue;
4426  }
4427  if (used_stations.empty()) {
4428  used_stations.reserve(2);
4429  used_stations.emplace_back(first_station, 0);
4430  }
4431  used_stations.emplace_back(st, 0);
4432  }
4433 
4434  /* no stations around at all? */
4435  if (first_station == nullptr) return 0;
4436 
4437  if (used_stations.empty()) {
4438  /* only one station around */
4439  amount *= first_station->goods[type].rating + 1;
4440  return UpdateStationWaiting(first_station, type, amount, source_type, source_id);
4441  }
4442 
4443  uint company_best[OWNER_NONE + 1] = {}; // best rating for each company, including OWNER_NONE
4444  uint company_sum[OWNER_NONE + 1] = {}; // sum of ratings for each company
4445  uint best_rating = 0;
4446  uint best_sum = 0; // sum of best ratings for each company
4447 
4448  for (auto &p : used_stations) {
4449  auto owner = p.first->owner;
4450  auto rating = p.first->goods[type].rating;
4451  if (rating > company_best[owner]) {
4452  best_sum += rating - company_best[owner]; // it's usually faster than iterating companies later
4453  company_best[owner] = rating;
4454  if (rating > best_rating) best_rating = rating;
4455  }
4456  company_sum[owner] += rating;
4457  }
4458 
4459  /* From now we'll calculate with fractional cargo amounts.
4460  * First determine how much cargo we really have. */
4461  amount *= best_rating + 1;
4462 
4463  uint moving = 0;
4464  for (auto &p : used_stations) {
4465  uint owner = p.first->owner;
4466  /* Multiply the amount by (company best / sum of best for each company) to get cargo allocated to a company
4467  * and by (station rating / sum of ratings in a company) to get the result for a single station. */
4468  p.second = amount * company_best[owner] * p.first->goods[type].rating / best_sum / company_sum[owner];
4469  moving += p.second;
4470  }
4471 
4472  /* If there is some cargo left due to rounding issues distribute it among the best rated stations. */
4473  if (amount > moving) {
4474  std::stable_sort(used_stations.begin(), used_stations.end(), [type](const StationInfo &a, const StationInfo &b) {
4475  return b.first->goods[type].rating < a.first->goods[type].rating;
4476  });
4477 
4478  assert(amount - moving <= used_stations.size());
4479  for (uint i = 0; i < amount - moving; i++) {
4480  used_stations[i].second++;
4481  }
4482  }
4483 
4484  uint moved = 0;
4485  for (auto &p : used_stations) {
4486  moved += UpdateStationWaiting(p.first, type, p.second, source_type, source_id);
4487  }
4488 
4489  return moved;
4490 }
4491 
4492 void UpdateStationDockingTiles(Station *st)
4493 {
4494  st->docking_station.Clear();
4495 
4496  /* For neutral stations, start with the industry area instead of dock area */
4497  const TileArea *area = st->industry != nullptr ? &st->industry->location : &st->ship_station;
4498 
4499  if (area->tile == INVALID_TILE) return;
4500 
4501  int x = TileX(area->tile);
4502  int y = TileY(area->tile);
4503 
4504  /* Expand the area by a tile on each side while
4505  * making sure that we remain inside the map. */
4506  int x2 = std::min<int>(x + area->w + 1, Map::SizeX());
4507  int x1 = std::max<int>(x - 1, 0);
4508 
4509  int y2 = std::min<int>(y + area->h + 1, Map::SizeY());
4510  int y1 = std::max<int>(y - 1, 0);
4511 
4512  TileArea ta(TileXY(x1, y1), TileXY(x2 - 1, y2 - 1));
4513  for (TileIndex tile : ta) {
4514  if (IsValidTile(tile) && IsPossibleDockingTile(tile)) CheckForDockingTile(tile);
4515  }
4516 }
4517 
4518 void BuildOilRig(TileIndex tile)
4519 {
4520  if (!Station::CanAllocateItem()) {
4521  Debug(misc, 0, "Can't allocate station for oilrig at 0x{:X}, reverting to oilrig only", tile);
4522  return;
4523  }
4524 
4525  Station *st = new Station(tile);
4526  _station_kdtree.Insert(st->index);
4527  st->town = ClosestTownFromTile(tile, UINT_MAX);
4528 
4529  st->string_id = GenerateStationName(st, tile, STATIONNAMING_OILRIG);
4530 
4531  assert(IsTileType(tile, MP_INDUSTRY));
4532  /* Mark industry as associated both ways */
4533  st->industry = Industry::GetByTile(tile);
4534  st->industry->neutral_station = st;
4535  DeleteAnimatedTile(tile);
4536  MakeOilrig(tile, st->index, GetWaterClass(tile));
4537 
4538  st->owner = OWNER_NONE;
4539  st->airport.type = AT_OILRIG;
4540  st->airport.Add(tile);
4541  st->ship_station.Add(tile);
4544  UpdateStationDockingTiles(st);
4545 
4546  st->rect.BeforeAddTile(tile, StationRect::ADD_FORCE);
4547 
4548  st->UpdateVirtCoord();
4549 
4550  /* An industry tile has now been replaced with a station tile, this may change the overlap between station catchments and industry tiles.
4551  * Recalculate the station catchment for all stations currently in the industry's nearby list.
4552  * Clear the industry's station nearby list first because Station::RecomputeCatchment cannot remove nearby industries in this case. */
4554  StationList nearby = std::move(st->industry->stations_near);
4555  st->industry->stations_near.clear();
4556  for (Station *near : nearby) {
4557  near->RecomputeCatchment(true);
4558  UpdateStationAcceptance(near, true);
4559  }
4560  }
4561 
4562  st->RecomputeCatchment();
4563  UpdateStationAcceptance(st, false);
4564 }
4565 
4566 void DeleteOilRig(TileIndex tile)
4567 {
4568  Station *st = Station::GetByTile(tile);
4569 
4570  MakeWaterKeepingClass(tile, OWNER_NONE);
4571 
4572  /* The oil rig station is not supposed to be shared with anything else */
4573  assert(st->facilities == (FACIL_AIRPORT | FACIL_DOCK) && st->airport.type == AT_OILRIG);
4574  if (st->industry != nullptr && st->industry->neutral_station == st) {
4575  /* Don't leave dangling neutral station pointer */
4576  st->industry->neutral_station = nullptr;
4577  }
4578  delete st;
4579 }
4580 
4581 static void ChangeTileOwner_Station(TileIndex tile, Owner old_owner, Owner new_owner)
4582 {
4583  if (IsAnyRoadStopTile(tile)) {
4584  for (RoadTramType rtt : _roadtramtypes) {
4585  /* Update all roadtypes, no matter if they are present */
4586  if (GetRoadOwner(tile, rtt) == old_owner) {
4587  RoadType rt = GetRoadType(tile, rtt);
4588  if (rt != INVALID_ROADTYPE) {
4589  /* A drive-through road-stop has always two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
4590  Company::Get(old_owner)->infrastructure.road[rt] -= 2;
4591  if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.road[rt] += 2;
4592  }
4593  SetRoadOwner(tile, rtt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
4594  }
4595  }
4596  }
4597 
4598  if (!IsTileOwner(tile, old_owner)) return;
4599 
4600  if (new_owner != INVALID_OWNER) {
4601  /* Update company infrastructure counts. Only do it here
4602  * if the new owner is valid as otherwise the clear
4603  * command will do it for us. No need to dirty windows
4604  * here, we'll redraw the whole screen anyway.*/
4605  Company *old_company = Company::Get(old_owner);
4606  Company *new_company = Company::Get(new_owner);
4607 
4608  /* Update counts for underlying infrastructure. */
4609  switch (GetStationType(tile)) {
4610  case STATION_RAIL:
4611  case STATION_WAYPOINT:
4612  if (!IsStationTileBlocked(tile)) {
4613  old_company->infrastructure.rail[GetRailType(tile)]--;
4614  new_company->infrastructure.rail[GetRailType(tile)]++;
4615  }
4616  break;
4617 
4618  case STATION_BUS:
4619  case STATION_TRUCK:
4620  case STATION_ROADWAYPOINT:
4621  /* Road stops were already handled above. */
4622  break;
4623 
4624  case STATION_BUOY:
4625  case STATION_DOCK:
4626  if (GetWaterClass(tile) == WATER_CLASS_CANAL) {
4627  old_company->infrastructure.water--;
4628  new_company->infrastructure.water++;
4629  }
4630  break;
4631 
4632  default:
4633  break;
4634  }
4635 
4636  /* Update station tile count. */
4637  if (!IsBuoy(tile) && !IsAirport(tile)) {
4638  old_company->infrastructure.station--;
4639  new_company->infrastructure.station++;
4640  }
4641 
4642  /* for buoys, owner of tile is owner of water, st->owner == OWNER_NONE */
4643  SetTileOwner(tile, new_owner);
4645  } else {
4646  if (IsDriveThroughStopTile(tile)) {
4647  /* Remove the drive-through road stop */
4648  if (IsRoadWaypoint(tile)) {
4650  } else {
4651  Command<CMD_REMOVE_ROAD_STOP>::Do(DC_EXEC | DC_BANKRUPT, tile, 1, 1, (GetStationType(tile) == STATION_TRUCK) ? ROADSTOP_TRUCK : ROADSTOP_BUS, false);
4652  }
4653  assert(IsTileType(tile, MP_ROAD));
4654  /* Change owner of tile and all roadtypes */
4655  ChangeTileOwner(tile, old_owner, new_owner);
4656  } else {
4658  /* Set tile owner of water under (now removed) buoy and dock to OWNER_NONE.
4659  * Update owner of buoy if it was not removed (was in orders).
4660  * Do not update when owned by OWNER_WATER (sea and rivers). */
4661  if ((IsTileType(tile, MP_WATER) || IsBuoyTile(tile)) && IsTileOwner(tile, old_owner)) SetTileOwner(tile, OWNER_NONE);
4662  }
4663  }
4664 }
4665 
4675 {
4676  /* Water flooding can always clear road stops. */
4677  if (_current_company == OWNER_WATER) return CommandCost();
4678 
4679  CommandCost ret;
4680 
4681  if (GetRoadTypeTram(tile) != INVALID_ROADTYPE) {
4682  Owner tram_owner = GetRoadOwner(tile, RTT_TRAM);
4683  if (tram_owner != OWNER_NONE) {
4684  ret = CheckOwnership(tram_owner);
4685  if (ret.Failed()) return ret;
4686  }
4687  }
4688 
4689  if (GetRoadTypeRoad(tile) != INVALID_ROADTYPE) {
4690  Owner road_owner = GetRoadOwner(tile, RTT_ROAD);
4691  if (road_owner == OWNER_TOWN) {
4692  ret = CheckAllowRemoveRoad(tile, GetAnyRoadBits(tile, RTT_ROAD), OWNER_TOWN, RTT_ROAD, flags);
4693  if (ret.Failed()) return ret;
4694  } else if (road_owner != OWNER_NONE) {
4695  ret = CheckOwnership(road_owner);
4696  if (ret.Failed()) return ret;
4697  }
4698  }
4699 
4700  return CommandCost();
4701 }
4702 
4710 {
4711  if (flags & DC_AUTO) {
4712  switch (GetStationType(tile)) {
4713  default: break;
4714  case STATION_RAIL: return_cmd_error(STR_ERROR_MUST_DEMOLISH_RAILROAD);
4715  case STATION_WAYPOINT: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
4716  case STATION_AIRPORT: return_cmd_error(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST);
4717  case STATION_TRUCK: return_cmd_error(HasTileRoadType(tile, RTT_TRAM) ? STR_ERROR_MUST_DEMOLISH_CARGO_TRAM_STATION_FIRST : STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
4718  case STATION_BUS: return_cmd_error(HasTileRoadType(tile, RTT_TRAM) ? STR_ERROR_MUST_DEMOLISH_PASSENGER_TRAM_STATION_FIRST : STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
4719  case STATION_ROADWAYPOINT: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
4720  case STATION_BUOY: return_cmd_error(STR_ERROR_BUOY_IN_THE_WAY);
4721  case STATION_DOCK: return_cmd_error(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST);
4722  case STATION_OILRIG:
4723  SetDParam(1, STR_INDUSTRY_NAME_OIL_RIG);
4724  return_cmd_error(STR_ERROR_GENERIC_OBJECT_IN_THE_WAY);
4725  }
4726  }
4727 
4728  switch (GetStationType(tile)) {
4729  case STATION_RAIL: return RemoveRailStation(tile, flags);
4730  case STATION_WAYPOINT: return RemoveRailWaypoint(tile, flags);
4731  case STATION_AIRPORT: return RemoveAirport(tile, flags);
4732  case STATION_TRUCK: [[fallthrough]];
4733  case STATION_BUS:
4734  if (IsDriveThroughStopTile(tile)) {
4735  CommandCost remove_road = CanRemoveRoadWithStop(tile, flags);
4736  if (remove_road.Failed()) return remove_road;
4737  }
4738  return RemoveRoadStop(tile, flags);
4739  case STATION_ROADWAYPOINT: {
4740  CommandCost remove_road = CanRemoveRoadWithStop(tile, flags);
4741  if (remove_road.Failed()) return remove_road;
4742  return RemoveRoadWaypointStop(tile, flags);
4743  }
4744  case STATION_BUOY: return RemoveBuoy(tile, flags);
4745  case STATION_DOCK: return RemoveDock(tile, flags);
4746  default: break;
4747  }
4748 
4749  return CMD_ERROR;
4750 }
4751 
4752 static CommandCost TerraformTile_Station(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
4753 {
4755  /* TODO: If you implement newgrf callback 149 'land slope check', you have to decide what to do with it here.
4756  * TTDP does not call it.
4757  */
4758  if (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new)) {
4759  switch (GetStationType(tile)) {
4760  case STATION_WAYPOINT:
4761  case STATION_RAIL: {
4762  DiagDirection direction = AxisToDiagDir(GetRailStationAxis(tile));
4763  if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
4764  if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
4765  return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4766  }
4767 
4768  case STATION_AIRPORT:
4769  return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4770 
4771  case STATION_TRUCK:
4772  case STATION_BUS: {
4773  DiagDirection direction = GetRoadStopDir(tile);
4774  if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
4775  if (IsDriveThroughStopTile(tile)) {
4776  if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
4777  }
4778  return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4779  }
4780 
4781  default: break;
4782  }
4783  }
4784  }
4785  return Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile);
4786 }
4787 
4793 uint FlowStat::GetShare(StationID st) const
4794 {
4795  uint32_t prev = 0;
4796  for (const auto &it : this->shares) {
4797  if (it.second == st) {
4798  return it.first - prev;
4799  } else {
4800  prev = it.first;
4801  }
4802  }
4803  return 0;
4804 }
4805 
4812 StationID FlowStat::GetVia(StationID excluded, StationID excluded2) const
4813 {
4814  if (this->unrestricted == 0) return INVALID_STATION;
4815  assert(!this->shares.empty());
4816  SharesMap::const_iterator it = this->shares.upper_bound(RandomRange(this->unrestricted));
4817  assert(it != this->shares.end() && it->first <= this->unrestricted);
4818  if (it->second != excluded && it->second != excluded2) return it->second;
4819 
4820  /* We've hit one of the excluded stations.
4821  * Draw another share, from outside its range. */
4822 
4823  uint end = it->first;
4824  uint begin = (it == this->shares.begin() ? 0 : (--it)->first);
4825  uint interval = end - begin;
4826  if (interval >= this->unrestricted) return INVALID_STATION; // Only one station in the map.
4827  uint new_max = this->unrestricted - interval;
4828  uint rand = RandomRange(new_max);
4829  SharesMap::const_iterator it2 = (rand < begin) ? this->shares.upper_bound(rand) :
4830  this->shares.upper_bound(rand + interval);
4831  assert(it2 != this->shares.end() && it2->first <= this->unrestricted);
4832  if (it2->second != excluded && it2->second != excluded2) return it2->second;
4833 
4834  /* We've hit the second excluded station.
4835  * Same as before, only a bit more complicated. */
4836 
4837  uint end2 = it2->first;
4838  uint begin2 = (it2 == this->shares.begin() ? 0 : (--it2)->first);
4839  uint interval2 = end2 - begin2;
4840  if (interval2 >= new_max) return INVALID_STATION; // Only the two excluded stations in the map.
4841  new_max -= interval2;
4842  if (begin > begin2) {
4843  Swap(begin, begin2);
4844  Swap(end, end2);
4845  Swap(interval, interval2);
4846  }
4847  rand = RandomRange(new_max);
4848  SharesMap::const_iterator it3 = this->shares.upper_bound(this->unrestricted);
4849  if (rand < begin) {
4850  it3 = this->shares.upper_bound(rand);
4851  } else if (rand < begin2 - interval) {
4852  it3 = this->shares.upper_bound(rand + interval);
4853  } else {
4854  it3 = this->shares.upper_bound(rand + interval + interval2);
4855  }
4856  assert(it3 != this->shares.end() && it3->first <= this->unrestricted);
4857  return it3->second;
4858 }
4859 
4866 {
4867  assert(!this->shares.empty());
4868  SharesMap new_shares;
4869  uint i = 0;
4870  for (const auto &it : this->shares) {
4871  new_shares[++i] = it.second;
4872  if (it.first == this->unrestricted) this->unrestricted = i;
4873  }
4874  this->shares.swap(new_shares);
4875  assert(!this->shares.empty() && this->unrestricted <= (--this->shares.end())->first);
4876 }
4877 
4884 void FlowStat::ChangeShare(StationID st, int flow)
4885 {
4886  /* We assert only before changing as afterwards the shares can actually
4887  * be empty. In that case the whole flow stat must be deleted then. */
4888  assert(!this->shares.empty());
4889 
4890  uint removed_shares = 0;
4891  uint added_shares = 0;
4892  uint last_share = 0;
4893  SharesMap new_shares;
4894  for (const auto &it : this->shares) {
4895  if (it.second == st) {
4896  if (flow < 0) {
4897  uint share = it.first - last_share;
4898  if (flow == INT_MIN || (uint)(-flow) >= share) {
4899  removed_shares += share;
4900  if (it.first <= this->unrestricted) this->unrestricted -= share;
4901  if (flow != INT_MIN) flow += share;
4902  last_share = it.first;
4903  continue; // remove the whole share
4904  }
4905  removed_shares += (uint)(-flow);
4906  } else {
4907  added_shares += (uint)(flow);
4908  }
4909  if (it.first <= this->unrestricted) this->unrestricted += flow;
4910 
4911  /* If we don't continue above the whole flow has been added or
4912  * removed. */
4913  flow = 0;
4914  }
4915  new_shares[it.first + added_shares - removed_shares] = it.second;
4916  last_share = it.first;
4917  }
4918  if (flow > 0) {
4919  new_shares[last_share + (uint)flow] = st;
4920  if (this->unrestricted < last_share) {
4921  this->ReleaseShare(st);
4922  } else {
4923  this->unrestricted += flow;
4924  }
4925  }
4926  this->shares.swap(new_shares);
4927 }
4928 
4934 void FlowStat::RestrictShare(StationID st)
4935 {
4936  assert(!this->shares.empty());
4937  uint flow = 0;
4938  uint last_share = 0;
4939  SharesMap new_shares;
4940  for (auto &it : this->shares) {
4941  if (flow == 0) {
4942  if (it.first > this->unrestricted) return; // Not present or already restricted.
4943  if (it.second == st) {
4944  flow = it.first - last_share;
4945  this->unrestricted -= flow;
4946  } else {
4947  new_shares[it.first] = it.second;
4948  }
4949  } else {
4950  new_shares[it.first - flow] = it.second;
4951  }
4952  last_share = it.first;
4953  }
4954  if (flow == 0) return;
4955  new_shares[last_share + flow] = st;
4956  this->shares.swap(new_shares);
4957  assert(!this->shares.empty());
4958 }
4959 
4965 void FlowStat::ReleaseShare(StationID st)
4966 {
4967  assert(!this->shares.empty());
4968  uint flow = 0;
4969  uint next_share = 0;
4970  bool found = false;
4971  for (SharesMap::reverse_iterator it(this->shares.rbegin()); it != this->shares.rend(); ++it) {
4972  if (it->first < this->unrestricted) return; // Note: not <= as the share may hit the limit.
4973  if (found) {
4974  flow = next_share - it->first;
4975  this->unrestricted += flow;
4976  break;
4977  } else {
4978  if (it->first == this->unrestricted) return; // !found -> Limit not hit.
4979  if (it->second == st) found = true;
4980  }
4981  next_share = it->first;
4982  }
4983  if (flow == 0) return;
4984  SharesMap new_shares;
4985  new_shares[flow] = st;
4986  for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4987  if (it->second != st) {
4988  new_shares[flow + it->first] = it->second;
4989  } else {
4990  flow = 0;
4991  }
4992  }
4993  this->shares.swap(new_shares);
4994  assert(!this->shares.empty());
4995 }
4996 
5002 void FlowStat::ScaleToMonthly(uint runtime)
5003 {
5004  assert(runtime > 0);
5005  SharesMap new_shares;
5006  uint share = 0;
5007  for (auto i : this->shares) {
5008  share = std::max(share + 1, i.first * 30 / runtime);
5009  new_shares[share] = i.second;
5010  if (this->unrestricted == i.first) this->unrestricted = share;
5011  }
5012  this->shares.swap(new_shares);
5013 }
5014 
5021 void FlowStatMap::AddFlow(StationID origin, StationID via, uint flow)
5022 {
5023  FlowStatMap::iterator origin_it = this->find(origin);
5024  if (origin_it == this->end()) {
5025  this->emplace(origin, FlowStat(via, flow));
5026  } else {
5027  origin_it->second.ChangeShare(via, flow);
5028  assert(!origin_it->second.GetShares()->empty());
5029  }
5030 }
5031 
5040 void FlowStatMap::PassOnFlow(StationID origin, StationID via, uint flow)
5041 {
5042  FlowStatMap::iterator prev_it = this->find(origin);
5043  if (prev_it == this->end()) {
5044  FlowStat fs(via, flow);
5045  fs.AppendShare(INVALID_STATION, flow);
5046  this->emplace(origin, fs);
5047  } else {
5048  prev_it->second.ChangeShare(via, flow);
5049  prev_it->second.ChangeShare(INVALID_STATION, flow);
5050  assert(!prev_it->second.GetShares()->empty());
5051  }
5052 }
5053 
5059 {
5060  for (auto &i : *this) {
5061  FlowStat &fs = i.second;
5062  uint local = fs.GetShare(INVALID_STATION);
5063  if (local > INT_MAX) { // make sure it fits in an int
5064  fs.ChangeShare(self, -INT_MAX);
5065  fs.ChangeShare(INVALID_STATION, -INT_MAX);
5066  local -= INT_MAX;
5067  }
5068  fs.ChangeShare(self, -(int)local);
5069  fs.ChangeShare(INVALID_STATION, -(int)local);
5070 
5071  /* If the local share is used up there must be a share for some
5072  * remote station. */
5073  assert(!fs.GetShares()->empty());
5074  }
5075 }
5076 
5084 {
5085  StationIDStack ret;
5086  for (FlowStatMap::iterator f_it = this->begin(); f_it != this->end();) {
5087  FlowStat &s_flows = f_it->second;
5088  s_flows.ChangeShare(via, INT_MIN);
5089  if (s_flows.GetShares()->empty()) {
5090  ret.Push(f_it->first);
5091  this->erase(f_it++);
5092  } else {
5093  ++f_it;
5094  }
5095  }
5096  return ret;
5097 }
5098 
5103 void FlowStatMap::RestrictFlows(StationID via)
5104 {
5105  for (auto &it : *this) {
5106  it.second.RestrictShare(via);
5107  }
5108 }
5109 
5114 void FlowStatMap::ReleaseFlows(StationID via)
5115 {
5116  for (auto &it : *this) {
5117  it.second.ReleaseShare(via);
5118  }
5119 }
5120 
5126 {
5127  uint ret = 0;
5128  for (const auto &it : *this) {
5129  ret += (--(it.second.GetShares()->end()))->first;
5130  }
5131  return ret;
5132 }
5133 
5139 uint FlowStatMap::GetFlowVia(StationID via) const
5140 {
5141  uint ret = 0;
5142  for (const auto &it : *this) {
5143  ret += it.second.GetShare(via);
5144  }
5145  return ret;
5146 }
5147 
5153 uint FlowStatMap::GetFlowFrom(StationID from) const
5154 {
5155  FlowStatMap::const_iterator i = this->find(from);
5156  if (i == this->end()) return 0;
5157  return (--(i->second.GetShares()->end()))->first;
5158 }
5159 
5166 uint FlowStatMap::GetFlowFromVia(StationID from, StationID via) const
5167 {
5168  FlowStatMap::const_iterator i = this->find(from);
5169  if (i == this->end()) return 0;
5170  return i->second.GetShare(via);
5171 }
5172 
5173 extern const TileTypeProcs _tile_type_station_procs = {
5174  DrawTile_Station, // draw_tile_proc
5175  GetSlopePixelZ_Station, // get_slope_z_proc
5176  ClearTile_Station, // clear_tile_proc
5177  nullptr, // add_accepted_cargo_proc
5178  GetTileDesc_Station, // get_tile_desc_proc
5179  GetTileTrackStatus_Station, // get_tile_track_status_proc
5180  ClickTile_Station, // click_tile_proc
5181  AnimateTile_Station, // animate_tile_proc
5182  TileLoop_Station, // tile_loop_proc
5183  ChangeTileOwner_Station, // change_tile_owner_proc
5184  nullptr, // add_produced_cargo_proc
5185  VehicleEnter_Station, // vehicle_enter_tile_proc
5186  GetFoundation_Station, // get_foundation_proc
5187  TerraformTile_Station, // terraform_tile_proc
5188 };
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
INVALID_RAILTYPE
@ INVALID_RAILTYPE
Flag for invalid railtype.
Definition: rail_type.h:34
AllocateSpecToStation
int AllocateSpecToStation(const StationSpec *statspec, BaseStation *st, bool exec)
Allocate a StationSpec to a Station.
Definition: newgrf_station.cpp:685
ROADSTOPTYPE_FREIGHT
@ ROADSTOPTYPE_FREIGHT
This RoadStop is for freight (truck) stops.
Definition: newgrf_roadstop.h:51
CC_MAIL
@ CC_MAIL
Mail.
Definition: cargotype.h:51
RoadVehicle
Buses, trucks and trams belong to this class.
Definition: roadveh.h:106
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
TileY
static debug_inline uint TileY(TileIndex tile)
Get the Y component of a tile.
Definition: map_func.h:437
TileInfo::z
int z
Height.
Definition: tile_cmd.h:48
ROADSTOP_BUS
@ ROADSTOP_BUS
A standard stop for buses.
Definition: station_type.h:46
TileDesc::airport_class
StringID airport_class
Name of the airport class.
Definition: tile_cmd.h:60
Vehicle::IsFrontEngine
debug_inline bool IsFrontEngine() const
Check if the vehicle is a front engine.
Definition: vehicle_base.h:945
MP_HOUSE
@ MP_HOUSE
A house by a town.
Definition: tile_type.h:51
RSF_DRAW_MODE_REGISTER
@ RSF_DRAW_MODE_REGISTER
Read draw mode from register 0x100.
Definition: newgrf_roadstop.h:76
DeleteNewGRFInspectWindow
void DeleteNewGRFInspectWindow(GrfSpecFeature feature, uint index)
Delete inspect window for a given feature and index.
Definition: newgrf_debug_gui.cpp:729
IsTileFlat
bool IsTileFlat(TileIndex tile, int *h)
Check if a given tile is flat.
Definition: tile_map.cpp:95
BaseStation::facilities
StationFacility facilities
The facilities that this station has.
Definition: base_station_base.h:70
TileDesc::grf
const char * grf
newGRF used for the tile contents
Definition: tile_cmd.h:63
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:3041
RemoveRailWaypoint
static CommandCost RemoveRailWaypoint(TileIndex tile, DoCommandFlag flags)
Remove a rail waypoint.
Definition: station_cmd.cpp:1865
VETSB_CANNOT_ENTER
@ VETSB_CANNOT_ENTER
The vehicle cannot enter the tile.
Definition: tile_cmd.h:38
VehicleCargoList::StoredCount
uint StoredCount() const
Returns sum of cargo on board the vehicle (ie not only reserved).
Definition: cargopacket.h:434
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:1971
TROPICZONE_DESERT
@ TROPICZONE_DESERT
Tile is desert.
Definition: tile_type.h:78
INVALID_AIRPORTTILE
static const uint INVALID_AIRPORTTILE
id for an invalid airport tile
Definition: airport.h:25
FlowStat::ScaleToMonthly
void ScaleToMonthly(uint runtime)
Scale all shares from link graph's runtime to monthly values.
Definition: station_cmd.cpp:5002
RoadTypeInfo
Definition: road.h:78
Station::docking_station
TileArea docking_station
Tile area the docking tiles cover.
Definition: station_base.h:455
AIRPORT_CLOSED_block
static const uint64_t AIRPORT_CLOSED_block
Dummy block for indicating a closed airport.
Definition: airport.h:128
ROTSG_GROUND
@ ROTSG_GROUND
Required: Main group of ground images.
Definition: road.h:62
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:1083
DIAGDIR_NE
@ DIAGDIR_NE
Northeast, upper right on your monitor.
Definition: direction_type.h:75
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:3208
Industry::owner
Owner owner
owner of the industry. Which SHOULD always be (imho) OWNER_NONE
Definition: industry.h:105
WID_SV_ACCEPT_RATING_LIST
@ WID_SV_ACCEPT_RATING_LIST
List of accepted cargoes / rating of cargoes.
Definition: station_widget.h:22
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:4865
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
SmallStack
Minimal stack that uses a pool to avoid pointers.
Definition: smallstack_type.hpp:135
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
Station::goods
GoodsEntry goods[NUM_CARGO]
Goods at this station.
Definition: station_base.h:468
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
StationRect
StationRect - used to track station spread out rectangle - cheaper than scanning whole map.
Definition: base_station_base.h:36
GoodsEntry::rating
uint8_t rating
Station rating for this cargo.
Definition: station_base.h:226
SetBit
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
Definition: bitmath_func.hpp:121
linkgraph_base.h
newgrf_station.h
newgrf_house.h
GetAcceptanceAroundStation
static CargoArray GetAcceptanceAroundStation(const Station *st, CargoTypes *always_accepted)
Get the acceptance of cargoes around the station in.
Definition: station_cmd.cpp:607
FlowStat::unrestricted
uint unrestricted
Limit for unrestricted shares.
Definition: station_base.h:144
Order::IsType
bool IsType(OrderType type) const
Check whether this order is of the given type.
Definition: order_base.h:70
Pool::PoolItem<&_industry_pool >::Get
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:339
GetDisallowedRoadDirections
DisallowedRoadDirections GetDisallowedRoadDirections(Tile t)
Gets the disallowed directions.
Definition: road_map.h:301
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:768
TimerGameTick::counter
static TickCounter counter
Monotonic counter, in ticks, since start of game.
Definition: timer_game_tick.h:60
IsRoadWaypointOnSnowOrDesert
static bool IsRoadWaypointOnSnowOrDesert(Tile t)
Check if a road waypoint tile has snow/desert.
Definition: station_map.h:310
station_kdtree.h
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
CC_LIQUID
@ CC_LIQUID
Liquids (Oil, Water, Rubber)
Definition: cargotype.h:56
FlowStatMap::GetFlowVia
uint GetFlowVia(StationID via) const
Get the sum of flows via a specific station from this FlowStatMap.
Definition: station_cmd.cpp:5139
Airport::GetHangarNum
uint GetHangarNum(TileIndex tile) const
Get the hangar number of the hangar at a specific tile.
Definition: station_base.h:387
CC_PASSENGERS
@ CC_PASSENGERS
Passengers.
Definition: cargotype.h:50
GameSettings::station
StationSettings station
settings related to station management
Definition: settings_type.h:605
DIR_E
@ DIR_E
East.
Definition: direction_type.h:28
SetWindowDirty
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition: window.cpp:3090
water.h
SetRailStationTileFlags
void SetRailStationTileFlags(TileIndex tile, const StationSpec *statspec)
Set rail station tile flags for the given tile.
Definition: station_cmd.cpp:1326
LinkGraph
A connected component of a link graph.
Definition: linkgraph.h:37
GetTileMaxZ
int GetTileMaxZ(TileIndex t)
Get top height of the tile inside the map.
Definition: tile_map.cpp:136
FACIL_TRAIN
@ FACIL_TRAIN
Station with train station.
Definition: station_type.h:54
StationSpec::renderdata
std::vector< NewGRFSpriteLayout > renderdata
Number of tile layouts.
Definition: newgrf_station.h:149
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
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
Station::AfterStationTileSetChange
void AfterStationTileSetChange(bool adding, StationType type)
After adding/removing tiles to station, update some station-related stuff.
Definition: station_cmd.cpp:753
FlowStatMap::GetFlow
uint GetFlow() const
Get the sum of all flows from this FlowStatMap.
Definition: station_cmd.cpp:5125
train.h
RoadBits
RoadBits
Enumeration for the road parts on a tile.
Definition: road_type.h:52
ValParamRailType
bool ValParamRailType(const RailType rail)
Validate functions for rail building.
Definition: rail.cpp:206
command_func.h
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
RoadStopSpec
Road stop specification.
Definition: newgrf_roadstop.h:135
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:663
ROADSTOP_END
@ ROADSTOP_END
End of valid types.
Definition: station_type.h:48
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:3025
Swap
constexpr void Swap(T &a, T &b)
Type safe swap operation.
Definition: math_func.hpp:283
Pool::PoolItem<&_link_graph_pool >::GetIfValid
static Titem * GetIfValid(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:350
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:4013
CMD_ERROR
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
Definition: command_func.h:28
UpdateAirplanesOnNewStation
void UpdateAirplanesOnNewStation(const Station *st)
Updates the status of the Aircraft heading or in the station.
Definition: aircraft_cmd.cpp:2162
TRACK_BIT_X
@ TRACK_BIT_X
X-axis track.
Definition: track_type.h:37
SetCustomRoadStopSpecIndex
void SetCustomRoadStopSpecIndex(Tile t, uint8_t specindex)
Set the custom road stop spec for this tile.
Definition: station_map.h:659
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:1273
FlatteningFoundation
Foundation FlatteningFoundation(Slope s)
Returns the foundation needed to flatten a slope.
Definition: slope_func.h:369
ROAD_Y
@ ROAD_Y
Full road along the y-axis (north-west + south-east)
Definition: road_type.h:59
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
GetRailTypeInfo
const RailTypeInfo * GetRailTypeInfo(RailType railtype)
Returns a pointer to the Railtype information for a given railtype.
Definition: rail.h:307
RailTypeInfo::GetRailtypeSpriteOffset
uint GetRailtypeSpriteOffset() const
Offset between the current railtype and normal rail.
Definition: rail.h:295
SSF_EXTENDED_FOUNDATIONS
@ SSF_EXTENDED_FOUNDATIONS
Extended foundation block instead of simple.
Definition: newgrf_station.h:101
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:3862
SAT_250_TICKS
@ SAT_250_TICKS
Trigger station every 250 ticks.
Definition: newgrf_animation_type.h:33
TO_BUILDINGS
@ TO_BUILDINGS
company buildings - depots, stations, HQ, ...
Definition: transparency.h:27
TileInfo
Tile information, used while rendering the tile.
Definition: tile_cmd.h:43
StationHandleBigTick
static bool StationHandleBigTick(BaseStation *st)
This function is called for each station once every 250 ticks.
Definition: station_cmd.cpp:3797
IsRailStation
bool IsRailStation(Tile t)
Is this station tile a rail station?
Definition: station_map.h:92
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:4965
GetWaterClass
WaterClass GetWaterClass(Tile t)
Get the water class at a tile.
Definition: water_map.h:115
SPRITE_WIDTH
@ SPRITE_WIDTH
number of bits for the sprite number
Definition: sprites.h:1535
TileDesc::railtype
StringID railtype
Type of rail on the tile.
Definition: tile_cmd.h:64
Town::statues
CompanyMask statues
which companies have a statue?
Definition: town.h:70
FACIL_DOCK
@ FACIL_DOCK
Station with a dock.
Definition: station_type.h:58
company_base.h
Vehicle::Next
Vehicle * Next() const
Get the next vehicle of this vehicle.
Definition: vehicle_base.h:632
tunnelbridge_map.h
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
GetAirport
const AirportFTAClass * GetAirport(const uint8_t airport_type)
Get the finite state machine of an airport type.
Definition: airport.cpp:207
BaseStation::town
Town * town
The town this station is associated with.
Definition: base_station_base.h:68
timer_game_calendar.h
SetRailStationPlatformReservation
void SetRailStationPlatformReservation(TileIndex start, DiagDirection dir, bool b)
Set the reservation for a complete station platform.
Definition: pbs.cpp:57
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:1165
CBM_CARGO_STATION_RATING_CALC
@ CBM_CARGO_STATION_RATING_CALC
custom station rating for this cargo type
Definition: newgrf_callbacks.h:357
TileDesc::owner
Owner owner[4]
Name of the owner(s)
Definition: tile_cmd.h:55
WATER_CLASS_SEA
@ WATER_CLASS_SEA
Sea.
Definition: water_map.h:48
CBID_STATION_AVAILABILITY
@ CBID_STATION_AVAILABILITY
Determine whether a newstation should be made available to build.
Definition: newgrf_callbacks.h:39
Station
Station data structure.
Definition: station_base.h:439
BaseStation::GetByTile
static BaseStation * GetByTile(TileIndex tile)
Get the base station belonging to a specific tile.
Definition: base_station_base.h:166
TRANSPORT_WATER
@ TRANSPORT_WATER
Transport over water.
Definition: transport_type.h:29
company_gui.h
GetTileSlope
Slope GetTileSlope(TileIndex tile)
Return the slope of a given tile inside the map.
Definition: tile_map.h:279
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
PALETTE_MODIFIER_COLOUR
@ PALETTE_MODIFIER_COLOUR
this bit is set when a recolouring process is in action
Definition: sprites.h:1550
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
INVALID_OWNER
@ INVALID_OWNER
An invalid owner.
Definition: company_type.h:29
elrail_func.h
AirportSpec::layouts
std::vector< AirportTileLayout > layouts
List of layouts composing the airport.
Definition: newgrf_airport.h:107
waypoint_cmd.h
StationSpec::callback_mask
uint8_t callback_mask
Bitmask of station callbacks that have to be called.
Definition: newgrf_station.h:159
AnimationInfo::triggers
uint16_t triggers
The triggers that trigger animation.
Definition: newgrf_animation_type.h:22
StringID
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
Definition: strings_type.h:16
Price
Price
Enumeration of all base prices for use with Prices.
Definition: economy_type.h:89
AirportSpec::name
StringID name
name of this airport
Definition: newgrf_airport.h:115
CanRemoveRoadWithStop
static CommandCost CanRemoveRoadWithStop(TileIndex tile, DoCommandFlag flags)
Check if a drive-through road stop tile can be cleared.
Definition: station_cmd.cpp:4674
StationClassID
StationClassID
Definition: newgrf_station.h:86
CMSAWater
static bool CMSAWater(TileIndex tile)
Check whether the tile is water.
Definition: station_cmd.cpp:198
SLOPE_FLAT
@ SLOPE_FLAT
a flat tile
Definition: slope_type.h:49
SAT_NEW_CARGO
@ SAT_NEW_CARGO
Trigger station on new cargo arrival.
Definition: newgrf_animation_type.h:28
TileDesc::station_class
StringID station_class
Class of station.
Definition: tile_cmd.h:58
RemoveRailStation
CommandCost RemoveRailStation(T *st, DoCommandFlag flags, Money removal_cost)
Remove a rail station/waypoint.
Definition: station_cmd.cpp:1810
TileDesc::road_speed
uint16_t road_speed
Speed limit of road (bridges and track)
Definition: tile_cmd.h:67
GetRoadWaypointRoadside
static Roadside GetRoadWaypointRoadside(Tile tile)
Get the decorations of a road waypoint.
Definition: station_map.h:288
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
BitmapTileIterator
Iterator to iterate over all tiles belonging to a bitmaptilearea.
Definition: bitmap_type.h:106
road_func.h
IntervalTimer
An interval timer will fire every interval, and will continue to fire until it is deleted.
Definition: timer.h:76
GB
constexpr static debug_inline 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
AAT_BUILT
@ AAT_BUILT
Triggered when the airport is built (for all tiles at the same time).
Definition: newgrf_animation_type.h:47
LinkGraphSchedule::instance
static LinkGraphSchedule instance
Static instance of LinkGraphSchedule.
Definition: linkgraphschedule.h:52
AutoslopeEnabled
bool AutoslopeEnabled()
Tests if autoslope is enabled for _current_company.
Definition: autoslope.h:44
Owner
Owner
Enum for all companies/owners.
Definition: company_type.h:18
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:1926
RailType
RailType
Enumeration for all possible railtypes.
Definition: rail_type.h:27
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
GetRegister
uint32_t GetRegister(uint i)
Gets the value of a so-called newgrf "register".
Definition: newgrf_spritegroup.h:29
Pool::PoolItem::index
Tindex index
Index of this pool item.
Definition: pool_type.hpp:238
RoadStopDrawMode
RoadStopDrawMode
Different draw modes to disallow rendering of some parts of the stop or road.
Definition: newgrf_roadstop.h:61
DrawRoadCatenary
void DrawRoadCatenary(const TileInfo *ti)
Draws the catenary for the given tile.
Definition: road_cmd.cpp:1451
RVSB_IN_ROAD_STOP
@ RVSB_IN_ROAD_STOP
The vehicle is in a road stop.
Definition: roadveh.h:49
CargoSpec::Get
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
Definition: cargotype.h:134
DiagDirToAxis
Axis DiagDirToAxis(DiagDirection d)
Convert a DiagDirection to the axis.
Definition: direction_func.h:214
CmdOpenCloseAirport
CommandCost CmdOpenCloseAirport(DoCommandFlag flags, StationID station_id)
Open/close an airport to incoming aircraft.
Definition: station_cmd.cpp:2746
VEH_TRAIN
@ VEH_TRAIN
Train vehicle type.
Definition: vehicle_type.h:24
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
GetAcceptanceMask
CargoTypes GetAcceptanceMask(const Station *st)
Get a mask of the cargo types that the station accepts.
Definition: station_cmd.cpp:501
CargoArray
Class for storing amounts of cargo.
Definition: cargo_type.h:114
PalSpriteID::sprite
SpriteID sprite
The 'real' sprite.
Definition: gfx_type.h:24
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:5040
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
GameSettings::difficulty
DifficultySettings difficulty
settings related to the difficulty
Definition: settings_type.h:593
GetTileZ
int GetTileZ(TileIndex tile)
Get bottom height of the tile.
Definition: tile_map.cpp:116
ship.h
CBID_CARGO_STATION_RATING_CALC
@ CBID_CARGO_STATION_RATING_CALC
Called to calculate part of a station rating.
Definition: newgrf_callbacks.h:200
INVALID_TILE
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition: tile_type.h:95
IsOilRig
bool IsOilRig(Tile t)
Is tile t part of an oilrig?
Definition: station_map.h:361
RailTypeInfo
This struct contains all the info that is needed to draw and construct tracks.
Definition: rail.h:127
VETSB_CONTINUE
@ VETSB_CONTINUE
Bit sets of the above specified bits.
Definition: tile_cmd.h:35
SetStationTileHaveWires
void SetStationTileHaveWires(Tile t, bool b)
Set the catenary wires state of the rail station.
Definition: station_map.h:460
Station::MoveSign
void MoveSign(TileIndex new_xy) override
Move the station main coordinate somewhere else.
Definition: station_cmd.cpp:464
Waypoint
Representation of a waypoint.
Definition: waypoint_base.h:23
CBM_STATION_SLOPE_CHECK
@ CBM_STATION_SLOPE_CHECK
Check slope of new station tiles.
Definition: newgrf_callbacks.h:314
SetStationTileHavePylons
void SetStationTileHavePylons(Tile t, bool b)
Set the catenary pylon state of the rail station.
Definition: station_map.h:484
station_land.h
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:537
RoadStop::GetByTile
static RoadStop * GetByTile(TileIndex tile, RoadStopType type)
Find a roadstop at given tile.
Definition: roadstop.cpp:266
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:2431
IsSteepSlope
static constexpr bool IsSteepSlope(Slope s)
Checks if a slope is steep.
Definition: slope_func.h:36
DifficultySettings::town_council_tolerance
uint8_t town_council_tolerance
minimum required town ratings to be allowed to demolish stuff
Definition: settings_type.h:116
IsRailStationTile
bool IsRailStationTile(Tile t)
Is this tile a station tile and a rail station?
Definition: station_map.h:102
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:1128
EUM_INCREASE
@ EUM_INCREASE
Increase capacity.
Definition: linkgraph_type.h:48
VEH_ROAD
@ VEH_ROAD
Road vehicle type.
Definition: vehicle_type.h:25
aircraft.h
TILE_SIZE
static const uint TILE_SIZE
Tile size in world coordinates.
Definition: tile_type.h:15
DiagDirection
DiagDirection
Enumeration for diagonal directions.
Definition: direction_type.h:73
Tile
Wrapper class to abstract away the way the tiles are stored.
Definition: map_func.h:25
CargoSpec::Iterate
static IterateWrapper Iterate(size_t from=0)
Returns an iterable ensemble of all valid CargoSpec.
Definition: cargotype.h:190
SpecializedStation< Station, false >::Get
static Station * Get(size_t index)
Gets station with given index.
Definition: base_station_base.h:254
_settings_client
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:56
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
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:39
Town::xy
TileIndex xy
town center tile
Definition: town.h:55
CargoSpec
Specification of a cargo type.
Definition: cargotype.h:71
GetRoadStopDir
DiagDirection GetRoadStopDir(Tile t)
Gets the direction the road stop entrance points towards.
Definition: station_map.h:344
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
MP_INDUSTRY
@ MP_INDUSTRY
Part of an industry.
Definition: tile_type.h:56
newgrf_debug.h
town.h
GetGRFConfig
GRFConfig * GetGRFConfig(uint32_t grfid, uint32_t mask)
Retrieve a NewGRF from the current config by its grfid.
Definition: newgrf_config.cpp:712
TileInfo::y
int y
Y position of the tile in unit coordinates.
Definition: tile_cmd.h:45
OrthogonalTileArea::Add
void Add(TileIndex to_add)
Add a single tile to a tile area; enlarge if needed.
Definition: tilearea.cpp:43
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > >
TileDesc::airport_tile_name
StringID airport_tile_name
Name of the airport tile.
Definition: tile_cmd.h:62
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
Company::infrastructure
CompanyInfrastructure infrastructure
NOSAVE: Counts of company owned infrastructure.
Definition: company_base.h:147
GetDockDirection
DiagDirection GetDockDirection(Tile t)
Get the direction of a dock.
Definition: station_map.h:588
VS_TRAIN_SLOWING
@ VS_TRAIN_SLOWING
Train is slowing down.
Definition: vehicle_base.h:37
LinkGraph::Size
NodeID Size() const
Get the current size of the component.
Definition: linkgraph.h:230
GetStationTileFlags
static StationSpec::TileFlags GetStationTileFlags(StationGfx gfx, const StationSpec *statspec)
Get station tile flags for the given StationGfx.
Definition: station_cmd.cpp:1314
RemoveRoadStop
static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags, int replacement_spec_index=-1)
Remove a bus station/truck stop.
Definition: station_cmd.cpp:2147
WC_STATION_VIEW
@ WC_STATION_VIEW
Station view; Window numbers:
Definition: window_type.h:345
IsWaterTile
bool IsWaterTile(Tile t)
Is it a water tile with plain water?
Definition: water_map.h:193
IndustrySpec::station_name
StringID station_name
Default name for nearby station.
Definition: industrytype.h:128
RoadStop::Enter
bool Enter(RoadVehicle *rv)
Enter the road stop.
Definition: roadstop.cpp:233
GoodsEntry::status
uint8_t status
Status of this cargo, see GoodsEntryStatus.
Definition: station_base.h:217
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
Vehicle
Vehicle data structure.
Definition: vehicle_base.h:244
Industry
Defines the internal data of a functional industry.
Definition: industry.h:68
RailTypeInfo::strings
struct RailTypeInfo::@26 strings
Strings associated with the rail type.
GetRailType
RailType GetRailType(Tile t)
Gets the rail type of the given tile.
Definition: rail_map.h:115
Vehicle::owner
Owner owner
Which company owns the vehicle?
Definition: vehicle_base.h:309
RestoreTrainReservation
static void RestoreTrainReservation(Train *v)
Restore platform reservation during station building/removing.
Definition: station_cmd.cpp:1251
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
DC_EXEC
@ DC_EXEC
execute the given command
Definition: command_type.h:376
PaletteID
uint32_t PaletteID
The number of the palette.
Definition: gfx_type.h:19
GameCreationSettings::landscape
uint8_t landscape
the landscape we're currently in
Definition: settings_type.h:368
FlowStatMap::FinalizeLocalConsumption
void FinalizeLocalConsumption(StationID self)
Subtract invalid flows from locally consumed flow.
Definition: station_cmd.cpp:5058
TriggerRoadStopRandomisation
void TriggerRoadStopRandomisation(Station *st, TileIndex tile, RoadStopRandomTrigger trigger, CargoID cargo_type=INVALID_CARGO)
Trigger road stop randomisation.
Definition: newgrf_roadstop.cpp:408
BaseStation::owner
Owner owner
The owner of this station.
Definition: base_station_base.h:69
Station::RecomputeCatchment
void RecomputeCatchment(bool no_clear_nearby_lists=false)
Recompute tiles covered in our catchment area.
Definition: station.cpp:469
MP_ROAD
@ MP_ROAD
A tile with road (or tram tracks)
Definition: tile_type.h:50
AirportSpec
Defines the data structure for an airport.
Definition: newgrf_airport.h:105
TileDesc
Tile description for the 'land area information' tool.
Definition: tile_cmd.h:52
FlowStat::GetShare
uint GetShare(StationID st) const
Get flow for a station.
Definition: station_cmd.cpp:4793
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
NewGRFClass::name
StringID name
Name of this class.
Definition: newgrf_class.h:49
HasExactlyOneBit
constexpr bool HasExactlyOneBit(T value)
Test whether value has exactly 1 bit set.
Definition: bitmath_func.hpp:278
TileDesc::airport_name
StringID airport_name
Name of the airport.
Definition: tile_cmd.h:61
CheckIfAuthorityAllowsNewStation
CommandCost CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags)
Checks whether the local authority allows construction of a new station (rail, road,...
Definition: town_cmd.cpp:3820
GetRailStationAxis
Axis GetRailStationAxis(Tile t)
Get the rail direction of a rail station.
Definition: station_map.h:496
ROADSTOP_TRUCK
@ ROADSTOP_TRUCK
A standard stop for trucks.
Definition: station_type.h:47
DoCommandFlag
DoCommandFlag
List of flags for a command.
Definition: command_type.h:374
Foundation
Foundation
Enumeration for Foundations.
Definition: slope_type.h:93
EdgeUpdateMode
EdgeUpdateMode
Special modes for updating links.
Definition: linkgraph_type.h:47
OrthogonalTileArea::h
uint16_t h
The height of the area.
Definition: tilearea_type.h:21
SourceType
SourceType
Types of cargo source and destination.
Definition: cargo_type.h:137
EnsureNoVehicleOnGround
CommandCost EnsureNoVehicleOnGround(TileIndex tile)
Ensure there is no vehicle at the ground at the given position.
Definition: vehicle.cpp:546
Vehicle::vehstatus
uint8_t vehstatus
Status.
Definition: vehicle_base.h:354
CompanyInfrastructure::station
uint32_t station
Count of company owned station tiles.
Definition: company_base.h:37
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
Industry::neutral_station
Station * neutral_station
Associated neutral station.
Definition: industry.h:98
Debug
#define Debug(category, level, format_string,...)
Ouptut a line of debugging information.
Definition: debug.h:37
CommandCost::Succeeded
bool Succeeded() const
Did this command succeed?
Definition: command_type.h:162
StationType
StationType
Station types.
Definition: station_type.h:31
TrackToTrackBits
TrackBits TrackToTrackBits(Track track)
Maps a Track to the corresponding TrackBits value.
Definition: track_func.h:77
pbs.h
Kdtree::Remove
void Remove(const T &element)
Remove a single element from the tree, if it exists.
Definition: kdtree.hpp:417
BaseStation::TileBelongsToRailStation
virtual bool TileBelongsToRailStation(TileIndex tile) const =0
Check whether a specific tile belongs to this station.
AAT_TILELOOP
@ AAT_TILELOOP
Triggered in the periodic tile loop.
Definition: newgrf_animation_type.h:48
BaseStation::string_id
StringID string_id
Default name (town area) of station.
Definition: base_station_base.h:65
GameSettings::game_creation
GameCreationSettings game_creation
settings used during the creation of a game (map)
Definition: settings_type.h:594
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
OrthogonalTileArea::Clear
void Clear()
Clears the 'tile area', i.e.
Definition: tilearea_type.h:40
FlowStatMap::RestrictFlows
void RestrictFlows(StationID via)
Restrict all flows at a station for specific cargo and destination.
Definition: station_cmd.cpp:5103
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
TRANSPORT_ROAD
@ TRANSPORT_ROAD
Transport by road vehicle.
Definition: transport_type.h:28
FlowStatMap::GetFlowFrom
uint GetFlowFrom(StationID from) const
Get the sum of flows from a specific station from this FlowStatMap.
Definition: station_cmd.cpp:5153
ROADSTOP_DRAW_MODE_OVERLAY
@ ROADSTOP_DRAW_MODE_OVERLAY
Drive-through stops: Draw the road overlay, e.g. pavement.
Definition: newgrf_roadstop.h:64
GetTownRadiusGroup
HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
Returns the bit corresponding to the town zone of the specified tile.
Definition: town_cmd.cpp:2439
Aircraft
Aircraft, helicopters, rotors and their shadows belong to this class.
Definition: aircraft.h:74
TileInfo::tileh
Slope tileh
Slope of the tile.
Definition: tile_cmd.h:46
SSF_SEPARATE_GROUND
@ SSF_SEPARATE_GROUND
Use different sprite set for ground sprites.
Definition: newgrf_station.h:97
RSF_NO_CATENARY
@ RSF_NO_CATENARY
Do not show catenary.
Definition: newgrf_roadstop.h:71
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
TRACK_BIT_NONE
@ TRACK_BIT_NONE
No track.
Definition: track_type.h:36
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:311
FlowStat
Flow statistics telling how much flow should be sent along a link.
Definition: station_base.h:32
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:2909
ChangeTileOwner
void ChangeTileOwner(TileIndex tile, Owner old_owner, Owner new_owner)
Change the owner of a tile.
Definition: landscape.cpp:564
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:243
GoodsEntry::cargo
StationCargoList cargo
The cargo packets of cargo waiting in this station.
Definition: station_base.h:210
LinkGraphSchedule::Queue
void Queue(LinkGraph *lg)
Queue a link graph for execution.
Definition: linkgraphschedule.h:67
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
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
Waypoint::UpdateVirtCoord
void UpdateVirtCoord() override
Update the virtual coords needed to draw the waypoint sign.
Definition: waypoint_cmd.cpp:42
RoadBuildCost
Money RoadBuildCost(RoadType roadtype)
Returns the cost of building the specified roadtype.
Definition: road.h:252
DrawTileSprites::ground
PalSpriteID ground
Palette and sprite for the ground.
Definition: sprite.h:59
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
IsDock
bool IsDock(Tile t)
Is tile t a dock tile?
Definition: station_map.h:372
AirportTileSpec
Defines the data structure of each individual tile of an airport.
Definition: newgrf_airporttiles.h:68
TileDesc::build_date
TimerGameCalendar::Date build_date
Date of construction of tile contents.
Definition: tile_cmd.h:57
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
IsTruckStop
bool IsTruckStop(Tile t)
Is the station at t a truck stop?
Definition: station_map.h:180
RailTypeInfo::name
StringID name
Name of this rail type.
Definition: rail.h:176
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:1348
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
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
newgrf_airporttiles.h
GameSettings::order
OrderSettings order
settings related to orders
Definition: settings_type.h:601
TransportType
TransportType
Available types of transport.
Definition: transport_type.h:19
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
DistanceManhattan
uint DistanceManhattan(TileIndex t0, TileIndex t1)
Gets the Manhattan distance between the two given tiles.
Definition: map.cpp:140
DIR_W
@ DIR_W
West.
Definition: direction_type.h:32
Airport::rotation
Direction rotation
How this airport is rotated.
Definition: station_base.h:296
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
FlowStatMap::DeleteFlows
StationIDStack DeleteFlows(StationID via)
Delete all flows at a station for specific cargo and destination.
Definition: station_cmd.cpp:5083
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
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
CheckForDockingTile
void CheckForDockingTile(TileIndex t)
Mark the supplied tile as a docking tile if it is suitable for docking.
Definition: water_cmd.cpp:184
CargoSpec::Index
CargoID Index() const
Determines index of this cargospec.
Definition: cargotype.h:105
LinkGraph::COMPRESSION_INTERVAL
static constexpr TimerGameEconomy::Date COMPRESSION_INTERVAL
Minimum number of days between subsequent compressions of a LG.
Definition: linkgraph.h:176
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:788
landscape_cmd.h
AnimationInfo::status
uint8_t status
Status; 0: no looping, 1: looping, 0xFF: no animation.
Definition: newgrf_animation_type.h:20
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
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:854
CheckOwnership
CommandCost CheckOwnership(Owner owner, TileIndex tile)
Check whether the current owner owns something.
Definition: company_cmd.cpp:363
VEH_INVALID
@ VEH_INVALID
Non-existing type of vehicle.
Definition: vehicle_type.h:35
Vehicle::dest_tile
TileIndex dest_tile
Heading for this tile.
Definition: vehicle_base.h:271
StationSettings::serve_neutral_industries
bool serve_neutral_industries
company stations can serve industries with attached neutral stations
Definition: settings_type.h:566
GetStationGfx
StationGfx GetStationGfx(Tile t)
Get the station graphics of this tile.
Definition: station_map.h:68
CargoSpec::classes
CargoClasses classes
Classes of this cargo type.
Definition: cargotype.h:78
return_cmd_error
#define return_cmd_error(errcode)
Returns from a function with a specific StringID as error.
Definition: command_func.h:38
StationFinder::stations
StationList stations
List of stations nearby.
Definition: station_type.h:103
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:970
Industry::produced
ProducedCargoes produced
produced cargo slots
Definition: industry.h:99
TrackBitsToTrackdirBits
TrackdirBits TrackBitsToTrackdirBits(TrackBits bits)
Converts TrackBits to TrackdirBits while allowing both directions.
Definition: track_func.h:319
ToTileIndexDiff
TileIndexDiff ToTileIndexDiff(TileIndexDiffC tidc)
Return the offset between two tiles from a TileIndexDiffC struct.
Definition: map_func.h:452
DIAGDIR_SE
@ DIAGDIR_SE
Southeast.
Definition: direction_type.h:76
IsBayRoadStopTile
bool IsBayRoadStopTile(Tile t)
Is tile t a bay (non-drive through) road stop station?
Definition: station_map.h:266
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
BaseStation::sign
TrackedViewportSign sign
NOSAVE: Dimensions of sign.
Definition: base_station_base.h:61
Industry::stations_near
StationList stations_near
NOSAVE: List of nearby stations.
Definition: industry.h:112
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
FlowStatMap::ReleaseFlows
void ReleaseFlows(StationID via)
Release all flows at a station for specific cargo and destination.
Definition: station_cmd.cpp:5114
M
#define M(x)
Helper for creating a bitset of slopes.
Definition: slope_type.h:84
CommandCost
Common return value for all commands.
Definition: command_type.h:23
Industry::location
TileArea location
Location of the industry.
Definition: industry.h:96
ApplyPixelFoundationToSlope
uint ApplyPixelFoundationToSlope(Foundation f, Slope &s)
Applies a foundation to a slope.
Definition: landscape.h:126
GetRailStationTrack
Track GetRailStationTrack(Tile t)
Get the rail track of a rail station tile.
Definition: station_map.h:508
IsWater
bool IsWater(Tile t)
Is it a plain water tile?
Definition: water_map.h:150
SetBitIterator
Iterable ensemble of each set bit in a value.
Definition: bitmath_func.hpp:301
RemoveFirstTrack
Track RemoveFirstTrack(TrackBits *tracks)
Removes first Track from TrackBits and returns it.
Definition: track_func.h:131
Train::GetVehicleTrackdir
Trackdir GetVehicleTrackdir() const override
Get the tracks of the train vehicle.
Definition: train_cmd.cpp:4225
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:241
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
RemoveAirport
static CommandCost RemoveAirport(TileIndex tile, DoCommandFlag flags)
Remove an airport.
Definition: station_cmd.cpp:2664
GRFConfig
Information about GRF, used in the game and (part of it) in savegames.
Definition: newgrf_config.h:147
CmdRemoveFromRoadWaypoint
CommandCost CmdRemoveFromRoadWaypoint(DoCommandFlag flags, TileIndex start, TileIndex end)
Remove road waypoints.
Definition: station_cmd.cpp:2413
clear_func.h
SetStationGfx
void SetStationGfx(Tile t, StationGfx gfx)
Set the station graphics of this tile.
Definition: station_map.h:80
StationGfx
uint8_t StationGfx
Copy from station_map.h.
Definition: newgrf_airport.h:22
BaseStation::train_station
TileArea train_station
Tile area the train 'station' part covers.
Definition: base_station_base.h:84
OWNER_NONE
@ OWNER_NONE
The tile has no ownership.
Definition: company_type.h:25
NF_INCOLOUR
@ NF_INCOLOUR
Bit value for coloured news.
Definition: news_type.h:74
Industry::GetByTile
static Industry * GetByTile(TileIndex tile)
Get the industry of the given tile.
Definition: industry.h:240
TrackBits
TrackBits
Allow incrementing of Track variables.
Definition: track_type.h:35
INVALID_DIAGDIR
@ INVALID_DIAGDIR
Flag for an invalid DiagDirection.
Definition: direction_type.h:80
DirtyCompanyInfrastructureWindows
void DirtyCompanyInfrastructureWindows(CompanyID company)
Redraw all windows with company infrastructure counts.
Definition: company_gui.cpp:2584
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
CalcClosestTownFromTile
Town * CalcClosestTownFromTile(TileIndex tile, uint threshold=UINT_MAX)
Return the town closest to the given tile within threshold.
Definition: town_cmd.cpp:3844
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:2535
WID_SV_ROADVEHS
@ WID_SV_ROADVEHS
List of scheduled road vehs button.
Definition: station_widget.h:28
Industry::type
IndustryType type
type of industry.
Definition: industry.h:104
roadstop_base.h
BaseStation::rect
StationRect rect
NOSAVE: Station spread out rectangle maintained by StationRect::xxx() functions.
Definition: base_station_base.h:85
Roadside
Roadside
The possible road side decorations.
Definition: road_map.h:477
TriggerWatchedCargoCallbacks
void TriggerWatchedCargoCallbacks(Station *st)
Run the watched cargo callback for all houses in the catchment area.
Definition: station_cmd.cpp:3771
DRD_NONE
@ DRD_NONE
None of the directions are disallowed.
Definition: road_type.h:74
GoodsEntry::HasRating
bool HasRating() const
Does this cargo have a rating at this station?
Definition: station_base.h:258
Vehicle::tile
TileIndex tile
Current tile index.
Definition: vehicle_base.h:264
RoadStopResolverObject
Road stop resolver.
Definition: newgrf_roadstop.h:110
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
autoslope.h
TileIterator
Base class for tile iterators.
Definition: tilearea_type.h:105
MayHaveRoad
bool MayHaveRoad(Tile t)
Test whether a tile can have road/tram types.
Definition: road_map.h:33
CMSAMine
static bool CMSAMine(TileIndex tile)
Check whether the tile is a mine.
Definition: station_cmd.cpp:171
DistanceFromEdge
uint DistanceFromEdge(TileIndex tile)
Param the minimum distance to an edge.
Definition: map.cpp:200
Station::MarkTilesDirty
void MarkTilesDirty(bool cargo_change) const
Marks the tiles of the station as dirty.
Definition: station.cpp:243
DIAGDIR_BEGIN
@ DIAGDIR_BEGIN
Used for iterations.
Definition: direction_type.h:74
Kdtree::Insert
void Insert(const T &element)
Insert a single element in the tree.
Definition: kdtree.hpp:398
TileDesc::roadtype
StringID roadtype
Type of road on the tile.
Definition: tile_cmd.h:66
RoadStopSpec::GetClearCost
Money GetClearCost(Price category) const
Get the cost for clearing a road stop of this type.
Definition: newgrf_roadstop.h:170
GetRailReservationTrackBits
TrackBits GetRailReservationTrackBits(Tile t)
Returns the reserved track bits of the tile.
Definition: rail_map.h:194
rail_cmd.h
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
_cheats
Cheats _cheats
All the cheats.
Definition: cheat.cpp:16
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
GoodsEntry::GetVia
StationID GetVia(StationID source) const
Get the best next hop for a cargo packet from station source.
Definition: station_base.h:268
TRACKDIR_BIT_NONE
@ TRACKDIR_BIT_NONE
No track build.
Definition: track_type.h:99
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
WATER_CLASS_INVALID
@ WATER_CLASS_INVALID
Used for industry tiles on land (also for oilrig if newgrf says so).
Definition: water_map.h:51
MP_WATER
@ MP_WATER
Water tile.
Definition: tile_type.h:54
Station::truck_station
TileArea truck_station
Tile area the truck 'station' part covers.
Definition: station_base.h:451
UpdateAirportsNoise
void UpdateAirportsNoise()
Recalculate the noise generated by the airports of each town.
Definition: station_cmd.cpp:2512
ReverseDiagDir
DiagDirection ReverseDiagDir(DiagDirection d)
Returns the reverse direction of the given DiagDirection.
Definition: direction_func.h:118
GoodsEntry::node
NodeID node
ID of node in link graph referring to this goods entry.
Definition: station_base.h:214
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
station_cmd.h
Vehicle::cargo
VehicleCargoList cargo
The cargo this vehicle is carrying.
Definition: vehicle_base.h:341
FreeTrainReservation
static void FreeTrainReservation(Train *v)
Clear platform reservation during station building/removing.
Definition: station_cmd.cpp:1239
CommandCost::Failed
bool Failed() const
Did this command fail?
Definition: command_type.h:171
FindRoadStopSpot
static RoadStop ** FindRoadStopSpot(bool truck_station, Station *st)
Definition: station_cmd.cpp:1881
station_func.h
Vehicle::current_order
Order current_order
The current order (+ status, like: loading)
Definition: vehicle_base.h:356
Airport::GetHangarTile
TileIndex GetHangarTile(uint hangar_num) const
Get the first tile of the given hangar.
Definition: station_base.h:358
VEH_SHIP
@ VEH_SHIP
Ship vehicle type.
Definition: vehicle_type.h:26
LinkGraph::BaseEdge
An edge in the link graph.
Definition: linkgraph.h:42
TRACK_BIT_LEFT
@ TRACK_BIT_LEFT
Left track.
Definition: track_type.h:41
Station::airport
Airport airport
Tile area the airport covers.
Definition: station_base.h:453
AirportTileTableIterator
Iterator to iterate over all tiles belonging to an airport spec.
Definition: newgrf_airport.h:31
OrthogonalTileArea
Represents the covered area of e.g.
Definition: tilearea_type.h:18
Station::AddFacility
void AddFacility(StationFacility new_facility_bit, TileIndex facil_xy)
Called when new facility is built on the station.
Definition: station.cpp:226
AxisToDiagDir
DiagDirection AxisToDiagDir(Axis a)
Converts an Axis to a DiagDirection.
Definition: direction_func.h:232
MultiMap::MapSize
size_t MapSize() const
Count the number of ranges with equal keys in this MultiMap.
Definition: multimap.hpp:347
EndSpriteCombine
void EndSpriteCombine()
Terminates a block of sprites started by StartSpriteCombine.
Definition: viewport.cpp:779
SourceID
uint16_t SourceID
Contains either industry ID, town ID or company ID (or INVALID_SOURCE)
Definition: cargo_type.h:143
DIAGDIR_SW
@ DIAGDIR_SW
Southwest.
Definition: direction_type.h:77
Town::MaxTownNoise
uint16_t MaxTownNoise() const
Calculate the max town noise.
Definition: town.h:125
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
CMSATree
static bool CMSATree(TileIndex tile)
Check whether the tile is a tree.
Definition: station_cmd.cpp:208
Vehicle::cur_speed
uint16_t cur_speed
current speed
Definition: vehicle_base.h:328
GetEmptyMask
CargoTypes GetEmptyMask(const Station *st)
Get a mask of the cargo types that are empty at the station.
Definition: station_cmd.cpp:516
SRT_NEW_CARGO
@ SRT_NEW_CARGO
Trigger station on new cargo arrival.
Definition: newgrf_station.h:106
ReverseTrackdir
Trackdir ReverseTrackdir(Trackdir trackdir)
Maps a trackdir to the reverse trackdir.
Definition: track_func.h:247
StationSpec::TileFlags::Blocked
@ Blocked
Tile is blocked to vehicles.
AirportTileSpec::GetByTile
static const AirportTileSpec * GetByTile(TileIndex tile)
Retrieve airport tile spec for the given airport tile.
Definition: newgrf_airporttiles.cpp:50
StationNameInformation::indtypes
std::bitset< NUM_INDUSTRYTYPES > indtypes
Bit set indicating when an industry type has been found.
Definition: station_cmd.cpp:227
TileDiffXY
TileIndexDiff TileDiffXY(int x, int y)
Calculates an offset for the given coordinate(-offset).
Definition: map_func.h:401
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:57
Station::indtype
IndustryType indtype
Industry type to get the name from.
Definition: station_base.h:457
IsTileOnWater
bool IsTileOnWater(Tile t)
Tests if the tile was built on water.
Definition: water_map.h:139
timer_game_tick.h
IsBuoyTile
bool IsBuoyTile(Tile t)
Is tile t a buoy tile?
Definition: station_map.h:403
RoadType
RoadType
The different roadtypes we support.
Definition: road_type.h:25
ANIM_STATUS_NO_ANIMATION
static const uint8_t ANIM_STATUS_NO_ANIMATION
There is no animation.
Definition: newgrf_animation_type.h:15
GameSettings::economy
EconomySettings economy
settings to change the economy
Definition: settings_type.h:603
_local_company
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Definition: company_cmd.cpp:52
RemoveDock
static CommandCost RemoveDock(TileIndex tile, DoCommandFlag flags)
Remove a dock.
Definition: station_cmd.cpp:2953
GetIndustryIndex
IndustryID GetIndustryIndex(Tile t)
Get the industry ID of the given tile.
Definition: industry_map.h:63
NewGRFSpriteLayout
NewGRF supplied spritelayout.
Definition: newgrf_commons.h:112
StationSpec::TileFlags::NoWires
@ NoWires
Tile should NOT contain catenary wires.
FindVehiclesWithOrder
void FindVehiclesWithOrder(VehiclePredicate veh_pred, OrderPredicate ord_pred, VehicleFunc veh_func)
Find vehicles matching an order.
Definition: vehiclelist_func.h:24
industry.h
safeguards.h
StationSpec::name
StringID name
Name of this station.
Definition: newgrf_station.h:128
timer.h
ROTSG_ROADSTOP
@ ROTSG_ROADSTOP
Required: Bay stop surface.
Definition: road.h:70
ClearTile_Station
CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags)
Clear a single tile of a station.
Definition: station_cmd.cpp:4709
NewGRFSpriteLayout::NeedsPreprocessing
bool NeedsPreprocessing() const
Tests whether this spritelayout needs preprocessing by PrepareLayout() and ProcessRegisters(),...
Definition: newgrf_commons.h:149
IsNormalRoadTile
static debug_inline bool IsNormalRoadTile(Tile t)
Return whether a tile is a normal road tile.
Definition: road_map.h:74
Train
'Train' is either a loco or a wagon.
Definition: train.h:89
_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.
FreeTrainTrackReservation
void FreeTrainTrackReservation(const Train *v)
Free the reserved path in front of a vehicle.
Definition: train_cmd.cpp:2391
HasTileRoadType
bool HasTileRoadType(Tile t, RoadTramType rtt)
Check if a tile has a road or a tram road type.
Definition: road_map.h:211
GetCanalSprite
SpriteID GetCanalSprite(CanalFeature feature, TileIndex tile)
Lookup the base sprite to use for a canal.
Definition: newgrf_canal.cpp:140
DirToDiagDir
DiagDirection DirToDiagDir(Direction dir)
Convert a Direction to a DiagDirection.
Definition: direction_func.h:166
SetCustomStationSpecIndex
void SetCustomStationSpecIndex(Tile t, uint8_t specindex)
Set the custom station spec for this tile.
Definition: station_map.h:623
LinkGraph::LastCompression
TimerGameEconomy::Date LastCompression() const
Get date of last compression.
Definition: linkgraph.h:236
SPRITE_MODIFIER_CUSTOM_SPRITE
@ SPRITE_MODIFIER_CUSTOM_SPRITE
Set when a sprite originates from an Action 1.
Definition: sprites.h:1547
NUM_AIRPORTS
@ NUM_AIRPORTS
Maximal number of airports in total.
Definition: airport.h:41
BaseStation::name
std::string name
Custom name.
Definition: base_station_base.h:64
DrawTileSprites
Ground palette sprite of a tile, together with its sprite layout.
Definition: sprite.h:58
RoadStopSpec::grf_prop
GRFFilePropsBase< NUM_CARGO+3 > grf_prop
Properties related the the grf file.
Definition: newgrf_roadstop.h:142
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:4934
GetTileOwner
Owner GetTileOwner(Tile tile)
Returns the owner of a tile.
Definition: tile_map.h:178
StartSpriteCombine
void StartSpriteCombine()
Starts a block of sprites, which are "combined" into a single bounding box.
Definition: viewport.cpp:769
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
RSF_DRIVE_THROUGH_ONLY
@ RSF_DRIVE_THROUGH_ONLY
Stop is drive-through only.
Definition: newgrf_roadstop.h:72
Station::bus_station
TileArea bus_station
Tile area the bus 'station' part covers.
Definition: station_base.h:449
RemoveBuoy
CommandCost RemoveBuoy(TileIndex tile, DoCommandFlag flags)
Remove a buoy.
Definition: waypoint_cmd.cpp:523
road_internal.h
INVALID_ROADTYPE
@ INVALID_ROADTYPE
flag for invalid roadtype
Definition: road_type.h:30
waypoint_func.h
RTSG_GROUND
@ RTSG_GROUND
Main group of ground images.
Definition: rail.h:52
airporttile_ids.h
FACIL_TRUCK_STOP
@ FACIL_TRUCK_STOP
Station with truck stops.
Definition: station_type.h:55
DeallocateSpecFromStation
void DeallocateSpecFromStation(BaseStation *st, uint8_t specindex)
Deallocate a StationSpec from a Station.
Definition: newgrf_station.cpp:727
TileIndexDiff
int32_t TileIndexDiff
An offset value between two tiles.
Definition: map_func.h:376
Point
Coordinates of a point in 2D.
Definition: geometry_type.hpp:21
TileDesc::station_name
StringID station_name
Type of station within the class.
Definition: tile_cmd.h:59
RoadTypeInfo::name
StringID name
Name of this rail type.
Definition: road.h:103
ValParamRoadType
bool ValParamRoadType(RoadType roadtype)
Validate functions for rail building.
Definition: road.cpp:153
GameSettings::linkgraph
LinkGraphSettings linkgraph
settings for link graph calculations
Definition: settings_type.h:604
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:4037
ToggleRoadWaypointOnSnowOrDesert
static void ToggleRoadWaypointOnSnowOrDesert(Tile t)
Toggle the snow/desert state of a road waypoint tile.
Definition: station_map.h:320
StationCargoList::AvailableCount
uint AvailableCount() const
Returns sum of cargo still available for loading at the sation.
Definition: cargopacket.h:588
GFX_DOCK_BASE_WATER_PART
static const int GFX_DOCK_BASE_WATER_PART
The offset for the water parts.
Definition: station_map.h:35
OffsetGroundSprite
void OffsetGroundSprite(int x, int y)
Called when a foundation has been drawn for the current tile.
Definition: viewport.cpp:601
GenerateStationName
static StringID GenerateStationName(Station *st, TileIndex tile, StationNaming name_class)
Definition: station_cmd.cpp:254
newgrf_roadstop.h
CombineTrackStatus
TrackStatus CombineTrackStatus(TrackdirBits trackdirbits, TrackdirBits red_signals)
Builds a TrackStatus.
Definition: track_func.h:388
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
ROADSIDE_BARREN
@ ROADSIDE_BARREN
Road on barren land.
Definition: road_map.h:478
CBM_STATION_AVAIL
@ CBM_STATION_AVAIL
Availability of station in construction window.
Definition: newgrf_callbacks.h:310
SpecializedStation< Station, false >::From
static Station * From(BaseStation *st)
Converts a BaseStation to SpecializedStation with type checking.
Definition: base_station_base.h:283
ROADSTOPTYPE_ALL
@ ROADSTOPTYPE_ALL
This RoadStop is for both types of station road stops.
Definition: newgrf_roadstop.h:52
NewGRFClass::GetSpec
const Tspec * GetSpec(uint index) const
Get a spec from the class at a given index.
Definition: newgrf_class_func.h:114
GetCustomRoadStopSpecIndex
uint GetCustomRoadStopSpecIndex(Tile t)
Get the custom road stop spec for this tile.
Definition: station_map.h:671
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
WID_SV_TRAINS
@ WID_SV_TRAINS
List of scheduled trains button.
Definition: station_widget.h:27
ShowStationViewWindow
void ShowStationViewWindow(StationID station)
Opens StationViewWindow for given station.
Definition: station_gui.cpp:2178
CommandCost::AddCost
void AddCost(const Money &cost)
Adds the given cost to the cost of the command.
Definition: command_type.h:63
TruncateCargo
static void TruncateCargo(const CargoSpec *cs, GoodsEntry *ge, uint amount=UINT_MAX)
Truncate the cargo by a specific amount.
Definition: station_cmd.cpp:3830
GUISettings::show_track_reservation
bool show_track_reservation
highlight reserved tracks.
Definition: settings_type.h:193
IsValidAxis
bool IsValidAxis(Axis d)
Checks if an integer value is a valid Axis.
Definition: direction_func.h:43
stdafx.h
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
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
TileTypeProcs
Set of callback functions for performing tile operations of a given tile type.
Definition: tile_cmd.h:158
StationFinder::GetStations
const StationList * GetStations()
Run a tile loop to find stations around a tile, on demand.
Definition: station_cmd.cpp:4367
SAT_BUILT
@ SAT_BUILT
Trigger tile when built.
Definition: newgrf_animation_type.h:27
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
GoodsEntry::link_graph
LinkGraphID link_graph
Link graph this station belongs to.
Definition: station_base.h:215
SetTileOwner
void SetTileOwner(Tile tile, Owner owner)
Sets the owner of a tile.
Definition: tile_map.h:198
Station::truck_stops
RoadStop * truck_stops
All the truck stops.
Definition: station_base.h:450
IndustrySpec
Defines the data structure for constructing industry.
Definition: industrytype.h:101
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
SpriteID
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition: gfx_type.h:18
CountBits
constexpr uint CountBits(T value)
Counts the number of set bits in a variable.
Definition: bitmath_func.hpp:262
Station::industry
Industry * industry
NOSAVE: Associated industry for neutral stations. (Rebuilt on load from Industry->st)
Definition: station_base.h:472
SetStationTileBlocked
void SetStationTileBlocked(Tile t, bool b)
Set the blocked state of the rail station.
Definition: station_map.h:436
Cheat::value
bool value
tells if the bool cheat is active or not
Definition: cheat_type.h:18
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
DC_BANKRUPT
@ DC_BANKRUPT
company bankrupts, skip money check, skip vehicle on tile check in some cases
Definition: command_type.h:382
AirportTileIterator
Iterator to iterate over all tiles belonging to an airport.
Definition: station_base.h:525
CompanyInfrastructure::rail
std::array< uint32_t, RAILTYPE_END > rail
Count of company owned track bits for each rail type.
Definition: company_base.h:33
CmdBuildDock
CommandCost CmdBuildDock(DoCommandFlag flags, TileIndex tile, StationID station_to_join, bool adjacent)
Build a dock/haven.
Definition: station_cmd.cpp:2802
AirportSpec::IsAvailable
bool IsAvailable() const
Check whether this airport is available to build.
Definition: newgrf_airport.cpp:82
RTSG_OVERLAY
@ RTSG_OVERLAY
Images for overlaying track.
Definition: rail.h:51
viewport_func.h
StationList
std::set< Station *, StationCompare > StationList
List of stations.
Definition: station_type.h:96
GetStationType
StationType GetStationType(Tile t)
Get the station type of this tile.
Definition: station_map.h:44
TileLoop_Water
void TileLoop_Water(TileIndex tile)
Let a water tile floods its diagonal adjoining tiles called from tunnelbridge_cmd,...
Definition: water_cmd.cpp:1231
bridge_map.h
OWNER_TOWN
@ OWNER_TOWN
A town owns the tile, or a town is expanding.
Definition: company_type.h:24
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
ROADSTOPTYPE_PASSENGER
@ ROADSTOPTYPE_PASSENGER
This RoadStop is for passenger (bus) stops.
Definition: newgrf_roadstop.h:50
animated_tile_func.h
HasTileWaterClass
bool HasTileWaterClass(Tile t)
Checks whether the tile has an waterclass associated.
Definition: water_map.h:104
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
TRACK_BIT_ALL
@ TRACK_BIT_ALL
All possible tracks.
Definition: track_type.h:50
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:673
StationSpec::disallowed_lengths
uint8_t disallowed_lengths
Bitmask of platform lengths available for the station.
Definition: newgrf_station.h:139
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:4131
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:1908
AXIS_X
@ AXIS_X
The X axis.
Definition: direction_type.h:117
IsValidTile
bool IsValidTile(Tile tile)
Checks if a tile is valid.
Definition: tile_map.h:161
yapf_cache.h
GetTrackBits
TrackBits GetTrackBits(Tile tile)
Gets the track bits of the given tile.
Definition: rail_map.h:136
Vehicle::direction
Direction direction
facing
Definition: vehicle_base.h:307
RailTypeInfo::max_speed
uint16_t max_speed
Maximum speed for vehicles travelling on this rail type.
Definition: rail.h:231
FlowStatMap::AddFlow
void AddFlow(StationID origin, StationID via, uint amount)
Add some flow from "origin", going via "via".
Definition: station_cmd.cpp:5021
IsTileForestIndustry
bool IsTileForestIndustry(TileIndex tile)
Check whether the tile is a forest.
Definition: industry_cmd.cpp:975
TileOffsByDiagDir
TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
Convert a DiagDirection to a TileIndexDiff.
Definition: map_func.h:565
Ticks::STATION_LINKGRAPH_TICKS
static constexpr TimerGameTick::Ticks STATION_LINKGRAPH_TICKS
Cycle duration for cleaning dead links.
Definition: timer_game_tick.h:80
DistanceMax
uint DistanceMax(TileIndex t0, TileIndex t1)
Gets the biggest distance component (x or y) between the two given tiles.
Definition: map.cpp:172
RailTypeInfo::single_x
SpriteID single_x
single piece of rail in X direction, without ground
Definition: rail.h:137
AirportSpec::size_x
uint8_t size_x
size of airport in x direction
Definition: newgrf_airport.h:109
MP_TREES
@ MP_TREES
Tile got trees.
Definition: tile_type.h:52
GetRoadTypeInfo
const RoadTypeInfo * GetRoadTypeInfo(RoadType roadtype)
Returns a pointer to the Roadtype information for a given roadtype.
Definition: road.h:227
TileIndexDiffC
A pair-construct of a TileIndexDiff.
Definition: map_type.h:31
GetAnimationFrame
uint8_t GetAnimationFrame(Tile t)
Get the current animation frame.
Definition: tile_map.h:250
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
DrawFoundation
void DrawFoundation(TileInfo *ti, Foundation f)
Draw foundation f at tile ti.
Definition: landscape.cpp:425
TRACK_BIT_UPPER
@ TRACK_BIT_UPPER
Upper track.
Definition: track_type.h:39
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:89
Map::SizeX
static debug_inline uint SizeX()
Get the size of the map along the X.
Definition: map_func.h:270
IsRoadWaypoint
bool IsRoadWaypoint(Tile t)
Is the station at t a road waypoint?
Definition: station_map.h:202
SSF_CUSTOM_FOUNDATIONS
@ SSF_CUSTOM_FOUNDATIONS
Draw custom foundations.
Definition: newgrf_station.h:100
TileDesc::tram_speed
uint16_t tram_speed
Speed limit of tram (bridges and track)
Definition: tile_cmd.h:69
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:29
FlowStat::empty_sharesmap
static const SharesMap empty_sharesmap
Static instance of FlowStat::SharesMap.
Definition: station_base.h:36
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
DT_MANUAL
@ DT_MANUAL
Manual distribution. No link graph calculations are run.
Definition: linkgraph_type.h:25
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:1649
string_func.h
IndustrySpec::enabled
bool enabled
entity still available (by default true).newgrf can disable it, though
Definition: industrytype.h:133
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
GoodsEntry::GES_CURRENT_MONTH
@ GES_CURRENT_MONTH
Set when cargo was delivered for final delivery this month.
Definition: station_base.h:201
CALLBACK_FAILED
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
Definition: newgrf_callbacks.h:420
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
IsValidDiagDirection
bool IsValidDiagDirection(DiagDirection d)
Checks if an integer value is a valid DiagDirection.
Definition: direction_func.h:21
Ship
All ships have this type.
Definition: ship.h:24
GoodsEntry
Stores station stats for a single cargo.
Definition: station_base.h:166
_current_company
CompanyID _current_company
Company currently doing an action.
Definition: company_cmd.cpp:53
vehicle_func.h
Track
Track
These are used to specify a single track.
Definition: track_type.h:19
WC_SELECT_STATION
@ WC_SELECT_STATION
Select station (when joining stations); Window numbers:
Definition: window_type.h:242
station_base.h
DeleteStationIfEmpty
static void DeleteStationIfEmpty(BaseStation *st)
This is called right after a station was deleted.
Definition: station_cmd.cpp:738
PALETTE_CRASH
static const PaletteID PALETTE_CRASH
Recolour sprite greying of crashed vehicles.
Definition: sprites.h:1610
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
IsBuoy
bool IsBuoy(Tile t)
Is tile t a buoy tile?
Definition: station_map.h:393
StationSpec
Station specification.
Definition: newgrf_station.h:115
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
TRACK_BIT_RIGHT
@ TRACK_BIT_RIGHT
Right track.
Definition: track_type.h:42
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
newgrf_roadtype.h
WATER_CLASS_CANAL
@ WATER_CLASS_CANAL
Canal.
Definition: water_map.h:49
AirportSpec::size_y
uint8_t size_y
size of airport in y direction
Definition: newgrf_airport.h:110
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
GoodsEntry::amount_fract
uint8_t amount_fract
Fractional part of the amount in the cargo list.
Definition: station_base.h:245
LinkGraph::AddNode
NodeID AddNode(const Station *st)
Add a node to the component and create empty edges associated with it.
Definition: linkgraph.cpp:149
refresh.h
Pool::PoolItem<&_town_pool >::GetNumItems
static size_t GetNumItems()
Returns number of valid items in the pool.
Definition: pool_type.hpp:369
DeleteAnimatedTile
void DeleteAnimatedTile(TileIndex tile)
Removes the given tile from the animated tile table.
Definition: animated_tile.cpp:25
Trackdir
Trackdir
Enumeration for tracks and directions.
Definition: track_type.h:67
IsDockingTile
bool IsDockingTile(Tile t)
Checks whether the tile is marked as a dockling tile.
Definition: water_map.h:374
RoadStop::ClearDriveThrough
void ClearDriveThrough()
Prepare for removal of this stop; update other neighbouring stops if needed.
Definition: roadstop.cpp:130
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
IsCustomStationSpecIndex
bool IsCustomStationSpecIndex(Tile t)
Is there a custom rail station spec on this tile?
Definition: station_map.h:611
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:804
Slope
Slope
Enumeration for the slope-type.
Definition: slope_type.h:48
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:2871
SpecializedVehicle< RoadVehicle, Type >::From
static RoadVehicle * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
Definition: vehicle_base.h:1215
ROADSIDE_GRASS
@ ROADSIDE_GRASS
Road on grass.
Definition: road_map.h:479
Axis
Axis
Allow incrementing of DiagDirDiff variables.
Definition: direction_type.h:116
IsRoadWaypointTile
bool IsRoadWaypointTile(Tile t)
Is this tile a station tile and a road waypoint?
Definition: station_map.h:212
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:2462
TRANSPORT_RAIL
@ TRANSPORT_RAIL
Transport by train.
Definition: transport_type.h:27
Map::Size
static debug_inline uint Size()
Get the size of the map.
Definition: map_func.h:288
AirportSpec::noise_level
uint8_t noise_level
noise that this airport generates
Definition: newgrf_airport.h:111
GoodsEntry::flows
FlowStatMap flows
Planned flows through this station.
Definition: station_base.h:211
RailTrackOffset
RailTrackOffset
Offsets for sprites within an overlay/underlay set.
Definition: rail.h:70
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
GetStationIndex
StationID GetStationIndex(Tile t)
Get StationID from a tile.
Definition: station_map.h:28
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
OrthogonalTileArea::tile
TileIndex tile
The base tile of the area.
Definition: tilearea_type.h:19
HasStationReservation
bool HasStationReservation(Tile t)
Get the reservation state of the rail station.
Definition: station_map.h:552
LinkGraph::MIN_TIMEOUT_DISTANCE
static const uint MIN_TIMEOUT_DISTANCE
Minimum effective distance for timeout calculation.
Definition: linkgraph.h:170
IsWaypointClass
bool IsWaypointClass(const RoadStopClass &cls)
Test if a RoadStopClass is the waypoint class.
Definition: newgrf_roadstop.h:200
ConstructionSettings::build_on_slopes
bool build_on_slopes
allow building on slopes
Definition: settings_type.h:383
ROTSG_OVERLAY
@ ROTSG_OVERLAY
Optional: Images for overlaying track.
Definition: road.h:61
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:3225
RSRT_NEW_CARGO
@ RSRT_NEW_CARGO
Trigger roadstop on arrival of new cargo.
Definition: newgrf_roadstop.h:38
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
RTO_X
@ RTO_X
Piece of rail in X direction.
Definition: rail.h:71
AirportSpec::grf_prop
struct GRFFileProps grf_prop
Properties related to the grf file.
Definition: newgrf_airport.h:121
OWNER_WATER
@ OWNER_WATER
The tile/execution is done by "water".
Definition: company_type.h:26
OrderList
Shared order list linking together the linked list of orders and the list of vehicles sharing this or...
Definition: order_base.h:259
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
cheat_type.h
RemoveRoadWaypointStop
CommandCost RemoveRoadWaypointStop(TileIndex tile, DoCommandFlag flags, int replacement_spec_index=-1)
Remove a road waypoint.
Definition: station_cmd.cpp:2262
GetAirportGfx
StationGfx GetAirportGfx(Tile t)
Get the station graphics of this airport tile.
Definition: station_map.h:332
HasSignals
bool HasSignals(Tile t)
Checks if a rail tile has signals.
Definition: rail_map.h:72
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:2054
Vehicle::NextShared
Vehicle * NextShared() const
Get the next vehicle of the shared vehicle chain.
Definition: vehicle_base.h:714
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, const NewsAllocatedData *data=nullptr)
Add a new newsitem to be shown.
Definition: news_gui.cpp:828
SetDockingTile
void SetDockingTile(Tile t, bool b)
Set the docking tile state of a tile.
Definition: water_map.h:364
FOUNDATION_LEVELED
@ FOUNDATION_LEVELED
The tile is leveled up to a flat slope.
Definition: slope_type.h:95
Station::UpdateVirtCoord
void UpdateVirtCoord() override
Update the virtual coords needed to draw the station sign.
Definition: station_cmd.cpp:442
StationNameInformation::free_names
uint32_t free_names
Current bitset of free names (we can remove names).
Definition: station_cmd.cpp:226
IsHangar
bool IsHangar(Tile t)
Check whether the given tile is a hangar.
Definition: station_cmd.cpp:92
WC_VEHICLE_DEPOT
@ WC_VEHICLE_DEPOT
Depot view; Window numbers:
Definition: window_type.h:351
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:1226
GetRoadOwner
Owner GetRoadOwner(Tile t, RoadTramType rtt)
Get the owner of a specific road type.
Definition: road_map.h:234
MP_STATION
@ MP_STATION
A tile of a station.
Definition: tile_type.h:53
RoadStopSpec::GetBuildCost
Money GetBuildCost(Price category) const
Get the cost for building a road stop of this type.
Definition: newgrf_roadstop.h:164
TimerGameConst< struct Economy >::INVALID_DATE
static constexpr TimerGame< struct Economy >::Date INVALID_DATE
Representation of an invalid date.
Definition: timer_game_common.h:193
IndustrySpec::grf_prop
GRFFileProps grf_prop
properties related to the grf file
Definition: industrytype.h:134
GoodsEntry::GES_ACCEPTANCE
@ GES_ACCEPTANCE
Set when the station accepts the cargo currently for final deliveries.
Definition: station_base.h:173
SpecializedStation< Station, false >::GetByTile
static Station * GetByTile(TileIndex tile)
Get the station belonging to a specific tile.
Definition: base_station_base.h:273
waypoint_base.h
StationSpec::TileFlags
TileFlags
Definition: newgrf_station.h:163
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
TrackedViewportSign::kdtree_valid
bool kdtree_valid
Are the sign data valid for use with the _viewport_sign_kdtree?
Definition: viewport_type.h:52
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
FindVehicleOnPos
void FindVehicleOnPos(TileIndex tile, void *data, VehicleFromPosProc *proc)
Find a vehicle from a specific location.
Definition: vehicle.cpp:505
UpdateCompanyRoadInfrastructure
void UpdateCompanyRoadInfrastructure(RoadType rt, Owner o, int count)
Update road infrastructure counts for a company.
Definition: road_cmd.cpp:190
RTO_Y
@ RTO_Y
Piece of rail in Y direction.
Definition: rail.h:72
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
HasRailCatenaryDrawn
bool HasRailCatenaryDrawn(RailType rt)
Test if we should draw rail catenary.
Definition: elrail_func.h:30
StationSpec::disallowed_platforms
uint8_t disallowed_platforms
Bitmask of number of platforms available for the station.
Definition: newgrf_station.h:134
FlowStat::GetVia
StationID GetVia() const
Get a station a package can be routed to.
Definition: station_base.h:130
CmdRemoveFromRailWaypoint
CommandCost CmdRemoveFromRailWaypoint(DoCommandFlag flags, TileIndex start, TileIndex end, bool keep_rail)
Remove a single tile from a waypoint.
Definition: station_cmd.cpp:1789
CargoID
uint8_t CargoID
Cargo slots to indicate a cargo type within a game.
Definition: cargo_type.h:22
DIAGDIR_END
@ DIAGDIR_END
Used for iterations.
Definition: direction_type.h:79
WPF_ROAD
@ WPF_ROAD
This is a road waypoint.
Definition: waypoint_base.h:19
Direction
Direction
Defines the 8 directions on the map.
Definition: direction_type.h:24
GetRoadBits
RoadBits GetRoadBits(Tile t, RoadTramType rtt)
Get the present road bits for a specific road type.
Definition: road_map.h:128
Station::catchment_tiles
BitmapTileArea catchment_tiles
NOSAVE: Set of individual tiles covered by catchment area.
Definition: station_base.h:459
LinkGraph::Merge
void Merge(LinkGraph *other)
Merge a link graph with another one.
Definition: linkgraph.cpp:90
CmdRemoveFromRailStation
CommandCost CmdRemoveFromRailStation(DoCommandFlag flags, TileIndex start, TileIndex end, bool keep_rail)
Remove a single tile from a rail station.
Definition: station_cmd.cpp:1756
IsBridgeAbove
bool IsBridgeAbove(Tile t)
checks if a bridge is set above the ground of this tile
Definition: bridge_map.h:45
TileDesc::str
StringID str
Description of the tile.
Definition: tile_cmd.h:53
TRACK_BIT_Y
@ TRACK_BIT_Y
Y-axis track.
Definition: track_type.h:38
RoadStop::next
RoadStop * next
Next stop of the given type at this station.
Definition: roadstop_base.h:69
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
GetTranslatedAirportTileID
StationGfx GetTranslatedAirportTileID(StationGfx gfx)
Do airporttile gfx ID translation for NewGRFs.
Definition: newgrf_airporttiles.cpp:96
DC_AUTO
@ DC_AUTO
don't allow building on structures
Definition: command_type.h:377
BaseStation::xy
TileIndex xy
Base tile of the station.
Definition: base_station_base.h:60
AddTrackToSignalBuffer
void AddTrackToSignalBuffer(TileIndex tile, Track track, Owner owner)
Add track to signal update buffer.
Definition: signal.cpp:592
NewGRFClass
Struct containing information relating to NewGRF classes for stations and airports.
Definition: newgrf_class.h:26
container_func.hpp
BaseStation
Base class for all station-ish types.
Definition: base_station_base.h:59
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
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:2769
Waypoint::road_waypoint_area
TileArea road_waypoint_area
Tile area the road waypoint part covers.
Definition: waypoint_base.h:26
RoadTypeInfo::strings
struct RoadTypeInfo::@29 strings
Strings associated with the rail type.
SetRoadOwner
void SetRoadOwner(Tile t, RoadTramType rtt, Owner o)
Set the owner of a specific road type.
Definition: road_map.h:251
IsReversingRoadTrackdir
bool IsReversingRoadTrackdir(Trackdir dir)
Checks whether the trackdir means that we are reversing.
Definition: track_func.h:673
ROAD_NONE
@ ROAD_NONE
No road-part is build.
Definition: road_type.h:53
WID_SV_SHIPS
@ WID_SV_SHIPS
List of scheduled ships button.
Definition: station_widget.h:29
SpecializedVehicle< Aircraft, VEH_AIRCRAFT >::Iterate
static Pool::IterateWrapper< Aircraft > Iterate(size_t from=0)
Returns an iterable ensemble of all valid vehicles of type T.
Definition: vehicle_base.h:1284
Waypoint::waypoint_flags
uint16_t waypoint_flags
Waypoint flags, see WaypointFlags.
Definition: waypoint_base.h:25
SetRoadWaypointRoadside
static void SetRoadWaypointRoadside(Tile tile, Roadside s)
Set the decorations of a road waypoint.
Definition: station_map.h:299
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
IndustrySpec::life_type
IndustryLifeType life_type
This is also known as Industry production flag, in newgrf specs.
Definition: industrytype.h:119
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::w
uint16_t w
The width of the area.
Definition: tilearea_type.h:20
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
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
TileArea
OrthogonalTileArea TileArea
Shorthand for the much more common orthogonal tile area.
Definition: tilearea_type.h:102
TriggerStationRandomisation
void TriggerStationRandomisation(Station *st, TileIndex trigger_tile, StationRandomTrigger trigger, CargoID cargo_type)
Trigger station randomisation.
Definition: newgrf_station.cpp:919
StationSettings::distant_join_stations
bool distant_join_stations
allow to join non-adjacent stations
Definition: settings_type.h:568
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:2328
Airport::GetNumHangars
uint GetNumHangars() const
Get the number of hangars on this airport.
Definition: station_base.h:394
GetRoadStopType
RoadStopType GetRoadStopType(Tile t)
Get the road stop type of this tile.
Definition: station_map.h:56
CommandHelper
Definition: command_func.h:93
SpriteGroup::Resolve
virtual const SpriteGroup * Resolve([[maybe_unused]] ResolverObject &object) const
Base sprite group resolver.
Definition: newgrf_spritegroup.h:61
DrawTileSprites::seq
const DrawTileSeqStruct * seq
Array of child sprites. Terminated with a terminator entry.
Definition: sprite.h:60
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
ROADSTOP_DRAW_MODE_ROAD
@ ROADSTOP_DRAW_MODE_ROAD
Bay stops: Draw the road itself.
Definition: newgrf_roadstop.h:63
StationSettings::adjacent_stations
bool adjacent_stations
allow stations to be built directly adjacent to other stations
Definition: settings_type.h:567
IsStationTileBlocked
bool IsStationTileBlocked(Tile t)
Is tile t a blocked tile?
Definition: station_map.h:424
RoadTypeInfo::max_speed
uint16_t max_speed
Maximum speed for vehicles travelling on this road type.
Definition: road.h:142
FACIL_BUS_STOP
@ FACIL_BUS_STOP
Station with bus stops.
Definition: station_type.h:56
Town
Town data structure.
Definition: town.h:54
StationSpec::grf_prop
GRFFilePropsBase< NUM_CARGO+3 > grf_prop
Properties related the the grf file.
Definition: newgrf_station.h:127
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
CargoPacket
Container for cargo from the same location and time.
Definition: cargopacket.h:40
TileXY
static debug_inline TileIndex TileXY(uint x, uint y)
Returns the TileIndex of a coordinate.
Definition: map_func.h:385
AirportSpec::depots
std::span< const HangarTileTable > depots
Position of the depots on the airports.
Definition: newgrf_airport.h:108
StationSettings::station_spread
uint8_t station_spread
amount a station may spread
Definition: settings_type.h:570
NewGRFSpecBase::class_index
Tindex class_index
Class index of this spec, invalid until class is allocated.
Definition: newgrf_class.h:18
random_func.hpp
GetTileMaxPixelZ
int GetTileMaxPixelZ(TileIndex tile)
Get top height of the tile.
Definition: tile_map.h:312
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
CBM_ROAD_STOP_AVAIL
@ CBM_ROAD_STOP_AVAIL
Availability of road stop in construction window.
Definition: newgrf_callbacks.h:321
RailTypeInfo::base_sprites
struct RailTypeInfo::@23 base_sprites
Struct containing the main sprites.
newgrf_canal.h
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
OverflowSafeInt< int64_t >
NF_SMALL
@ NF_SMALL
Small news item. (Information window with text and viewport)
Definition: news_type.h:80
Vehicle::IsStoppedInDepot
bool IsStoppedInDepot() const
Check whether the vehicle is in the depot and stopped.
Definition: vehicle_base.h:560
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
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
DrawRailCatenary
void DrawRailCatenary(const TileInfo *ti)
Draws overhead wires and pylons for electric railways.
Definition: elrail.cpp:568
IsShipDestinationTile
bool IsShipDestinationTile(TileIndex tile, StationID station)
Test if a tile is a docking tile for the given station.
Definition: ship_cmd.cpp:647
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
NEW_AIRPORTTILE_OFFSET
static const uint NEW_AIRPORTTILE_OFFSET
offset of first newgrf airport tile
Definition: airport.h:24
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
NewGRFSpriteLayout::GetLayout
const DrawTileSeqStruct * GetLayout(PalSpriteID *ground) const
Returns the result spritelayout after preprocessing.
Definition: newgrf_commons.h:162
VEH_AIRCRAFT
@ VEH_AIRCRAFT
Aircraft vehicle type.
Definition: vehicle_type.h:27
RoadStopType
RoadStopType
Types of RoadStops.
Definition: station_type.h:45
VETSB_ENTERED_STATION
@ VETSB_ENTERED_STATION
The vehicle entered a station.
Definition: tile_cmd.h:36
IsStationRoadStop
bool IsStationRoadStop(Tile t)
Is the station at t a road station?
Definition: station_map.h:223
Vehicle::cargo_type
CargoID cargo_type
type of cargo this vehicle is carrying
Definition: vehicle_base.h:342
GoodsEntry::max_waiting_cargo
uint max_waiting_cargo
Max cargo from this station waiting at any station.
Definition: station_base.h:213
IsValidCargoID
bool IsValidCargoID(CargoID t)
Test whether cargo type is not INVALID_CARGO.
Definition: cargo_type.h:107
OrthogonalTileArea::Expand
OrthogonalTileArea & Expand(int rad)
Expand a tile area by rad tiles in each direction, keeping within map bounds.
Definition: tilearea.cpp:123
Ticks::STATION_RATING_TICKS
static constexpr TimerGameTick::Ticks STATION_RATING_TICKS
Cycle duration for updating station rating.
Definition: timer_game_tick.h:78
WID_SV_CLOSE_AIRPORT
@ WID_SV_CLOSE_AIRPORT
'Close airport' button.
Definition: station_widget.h:26
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:684
WC_TOWN_VIEW
@ WC_TOWN_VIEW
Town view; Window numbers:
Definition: window_type.h:333
SetStationTileRandomBits
void SetStationTileRandomBits(Tile t, uint8_t random_bits)
Set the random bits for a station tile.
Definition: station_map.h:683
TileDesc::owner_type
StringID owner_type[4]
Type of each owner.
Definition: tile_cmd.h:56
GetIndustryType
IndustryType GetIndustryType(Tile tile)
Retrieve the type for this industry.
Definition: industry_cmd.cpp:106
AxisToTrackBits
TrackBits AxisToTrackBits(Axis a)
Maps an Axis to the corresponding TrackBits value.
Definition: track_func.h:88
Station::bus_stops
RoadStop * bus_stops
All the road stops.
Definition: station_base.h:448
RVS_IN_DT_ROAD_STOP
@ RVS_IN_DT_ROAD_STOP
The vehicle is in a drive-through road stop.
Definition: roadveh.h:46
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
Town::noise_reached
uint16_t noise_reached
level of noise that all the airports are generating
Definition: town.h:68
TileInfo::x
int x
X position of the tile in unit coordinates.
Definition: tile_cmd.h:44
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
LinkGraphSchedule::Unqueue
void Unqueue(LinkGraph *lg)
Remove a link graph from the execution queue.
Definition: linkgraphschedule.h:77
PalSpriteID::pal
PaletteID pal
The palette (use PAL_NONE) if not needed)
Definition: gfx_type.h:25
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
TimerGameCalendar::date
static Date date
Current date in days (day counter).
Definition: timer_game_calendar.h:34
TileInfo::tile
TileIndex tile
Tile index.
Definition: tile_cmd.h:47
NT_ACCEPTANCE
@ NT_ACCEPTANCE
A type of cargo is (no longer) accepted.
Definition: news_type.h:37
GameSettings::construction
ConstructionSettings construction
construction of things in-game
Definition: settings_type.h:595
StationSpec::TileFlags::Pylons
@ Pylons
Tile should contain catenary pylons.
FlowStat::shares
SharesMap shares
Shares of flow to be sent via specified station (or consumed locally).
Definition: station_base.h:143
GetAllRoadBits
RoadBits GetAllRoadBits(Tile tile)
Get all set RoadBits on the given tile.
Definition: road_map.h:141
Cheats::station_rating
Cheat station_rating
Fix station ratings at 100%.
Definition: cheat_type.h:35
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
ROADSIDE_PAVED
@ ROADSIDE_PAVED
Road with paved sidewalks.
Definition: road_map.h:480
IsDockTile
bool IsDockTile(Tile t)
Is tile t a dock tile?
Definition: station_map.h:382
GetIndustrySpec
const IndustrySpec * GetIndustrySpec(IndustryType thistype)
Accessor for array _industry_specs.
Definition: industry_cmd.cpp:123
IsAnyRoadStop
bool IsAnyRoadStop(Tile t)
Is the station at t a road station?
Definition: station_map.h:245
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:2391
OrderSettings::selectgoods
bool selectgoods
only send the goods to station if a train has been there
Definition: settings_type.h:483
TileDesc::rail_speed
uint16_t rail_speed
Speed limit of rail (bridges and track)
Definition: tile_cmd.h:65
GetSnowLine
uint8_t GetSnowLine()
Get the current snow line, either variable or static.
Definition: landscape.cpp:608
IsTileType
static debug_inline bool IsTileType(Tile tile, TileType type)
Checks if a tile is a given tiletype.
Definition: tile_map.h:150
IsRailWaypoint
bool IsRailWaypoint(Tile t)
Is this station tile a rail waypoint?
Definition: station_map.h:113
Vehicle::GetOrderStationLocation
virtual TileIndex GetOrderStationLocation([[maybe_unused]] StationID station)
Determine the location for the station where the vehicle goes to next.
Definition: vehicle_base.h:796
IndustrySpec::name
StringID name
Displayed name of the industry.
Definition: industrytype.h:123
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
RoadStop
A Stop for a Road Vehicle.
Definition: roadstop_base.h:22
BaseVehicle::type
VehicleType type
Type of vehicle.
Definition: vehicle_type.h:51
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
Clamp
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition: math_func.hpp:79
BaseStation::UpdateVirtCoord
virtual void UpdateVirtCoord()=0
Update the coordinated of the sign (as shown in the viewport).
GRFFilePropsBase::grffile
const struct GRFFile * grffile
grf file that introduced this entity
Definition: newgrf_commons.h:312
TileX
static debug_inline uint TileX(TileIndex tile)
Get the X component of a tile.
Definition: map_func.h:427
TileDesc::tramtype
StringID tramtype
Type of tram on the tile.
Definition: tile_cmd.h:68
AirportTileSpec::name
StringID name
Tile Subname string, land information on this tile will give you "AirportName (TileSubname)".
Definition: newgrf_airporttiles.h:70
SetAnimationFrame
void SetAnimationFrame(Tile t, uint8_t frame)
Set a new animation frame.
Definition: tile_map.h:262
TRACK_Y
@ TRACK_Y
Track along the y-axis (north-west to south-east)
Definition: track_type.h:22
FACIL_WAYPOINT
@ FACIL_WAYPOINT
Station is a waypoint.
Definition: station_type.h:59
WatchedCargoCallback
void WatchedCargoCallback(TileIndex tile, CargoTypes trigger_cargoes)
Run watched cargo accepted callback for a house.
Definition: newgrf_house.cpp:755
NUM_CARGO
static const CargoID NUM_CARGO
Maximum number of cargo types in a game.
Definition: cargo_type.h:74
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
Airport::psa
PersistentStorage * psa
Persistent storage for NewGRF airports.
Definition: station_base.h:298
NewGRFClass::GetClassCount
static uint GetClassCount()
Get the number of allocated classes.
Definition: newgrf_class_func.h:93
Airport::GetSpec
const AirportSpec * GetSpec() const
Get the AirportSpec that from the airport type of this airport.
Definition: station_base.h:305
AXIS_Y
@ AXIS_Y
The y axis.
Definition: direction_type.h:118
order_backup.h
WaterClass
WaterClass
classes of water (for WATER_TILE_CLEAR water tile type).
Definition: water_map.h:47
NewGRFClass::Get
static NewGRFClass * Get(Tindex class_index)
Get a particular class.
Definition: newgrf_class_func.h:82
AirportTileSpec::Get
static const AirportTileSpec * Get(StationGfx gfx)
Retrieve airport tile spec for the given airport tile.
Definition: newgrf_airporttiles.cpp:37
ShowDepotWindow
void ShowDepotWindow(TileIndex tile, VehicleType type)
Opens a depot window.
Definition: depot_gui.cpp:1141
Station::GetTileArea
void GetTileArea(TileArea *ta, StationType type) const override
Get the tile area for a given station type.
Definition: station_cmd.cpp:411
IsCargoInClass
bool IsCargoInClass(CargoID c, CargoClass cc)
Does cargo c have cargo class cc?
Definition: cargotype.h:233
Company
Definition: company_base.h:133
CMSAMatcher
bool(* CMSAMatcher)(TileIndex tile)
Function to check whether the given tile matches some criterion.
Definition: station_cmd.cpp:144
AirportFTAClass::AIRPLANES
@ AIRPLANES
Can planes land on this airport type?
Definition: airport.h:147
Airport::type
uint8_t type
Type of this airport,.
Definition: station_base.h:294
SpecializedVehicle::Last
T * Last()
Get the last vehicle in the chain.
Definition: vehicle_base.h:1118
Town::exclusivity
CompanyID exclusivity
which company has exclusivity
Definition: town.h:75
ClrBit
constexpr T ClrBit(T &x, const uint8_t y)
Clears a bit in a variable.
Definition: bitmath_func.hpp:151
IsTileOwner
bool IsTileOwner(Tile tile, Owner owner)
Checks if a tile belongs to the given owner.
Definition: tile_map.h:214
AirportTileSpec::grf_prop
GRFFileProps grf_prop
properties related the the grf file
Definition: newgrf_airporttiles.h:74
SetWindowClassesDirty
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
Definition: window.cpp:3116
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:3103
UpdateAllStationVirtCoords
void UpdateAllStationVirtCoords()
Update the virtual coords needed to draw the station sign for all stations.
Definition: station_cmd.cpp:476
NewGRFClass::GetSpecCount
uint GetSpecCount() const
Get the number of allocated specs within the class.
Definition: newgrf_class.h:70
GetTropicZone
TropicZone GetTropicZone(Tile tile)
Get the tropic zone.
Definition: tile_map.h:238
WC_STATION_LIST
@ WC_STATION_LIST
Station list; Window numbers:
Definition: window_type.h:302
Order::next
Order * next
Pointer to next order. If nullptr, end of list.
Definition: order_base.h:59
IsAnyRoadStopTile
bool IsAnyRoadStopTile(Tile t)
Is tile t a road stop station?
Definition: station_map.h:256
ShowWaypointWindow
void ShowWaypointWindow(const Waypoint *wp)
Show the window for the given waypoint.
Definition: waypoint_gui.cpp:223
TRACK_X
@ TRACK_X
Track along the x-axis (north-east to south-west)
Definition: track_type.h:21
GetInclinedSlopeDirection
DiagDirection GetInclinedSlopeDirection(Slope s)
Returns the direction of an inclined slope.
Definition: slope_func.h:239
Order
Definition: order_base.h:36
HasTileWaterGround
bool HasTileWaterGround(Tile t)
Checks whether the tile has water at the ground.
Definition: water_map.h:353
GetClosestDeletedStation
static Station * GetClosestDeletedStation(TileIndex tile)
Find the closest deleted station of the current company.
Definition: station_cmd.cpp:388
newgrf_cargo.h
Airport::layout
uint8_t layout
Airport layout number.
Definition: station_base.h:295
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:1211
GoodsEntry::GES_RATING
@ GES_RATING
This indicates whether a cargo has a rating at the station.
Definition: station_base.h:183
GoodsEntry::HasVehicleEverTriedLoading
bool HasVehicleEverTriedLoading() const
Reports whether a vehicle has ever tried to load the cargo at this station.
Definition: station_base.h:252
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
Ticks::STATION_ACCEPTANCE_TICKS
static constexpr TimerGameTick::Ticks STATION_ACCEPTANCE_TICKS
Cycle duration for updating station acceptance.
Definition: timer_game_tick.h:79
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:763
CompanyInfrastructure::water
uint32_t water
Count of company owned track bits for canals.
Definition: company_base.h:36
GetTileSlopeZ
std::tuple< Slope, int > GetTileSlopeZ(TileIndex tile)
Return the slope of a given tile inside the map.
Definition: tile_map.cpp:55
Town::exclusive_counter
uint8_t exclusive_counter
months till the exclusivity expires
Definition: town.h:76
SpriteGroup
Definition: newgrf_spritegroup.h:57
RoadVehicle::state
uint8_t state
Definition: roadveh.h:108
ROAD_X
@ ROAD_X
Full road along the x-axis (south-west + north-east)
Definition: road_type.h:58
Station::ship_station
TileArea ship_station
Tile area the ship 'station' part covers.
Definition: station_base.h:454
IsAirport
bool IsAirport(Tile t)
Is this station tile an airport?
Definition: station_map.h:157
RailTypeInfo::single_y
SpriteID single_y
single piece of rail in Y direction, without ground
Definition: rail.h:138
AxisToRoadBits
RoadBits AxisToRoadBits(Axis a)
Create the road-part which belongs to the given Axis.
Definition: road_func.h:111
FlowStat::ChangeShare
void ChangeShare(StationID st, int flow)
Change share for specified station.
Definition: station_cmd.cpp:4884
VehicleEnterTileStatus
VehicleEnterTileStatus
The returned bits of VehicleEnterTile.
Definition: tile_cmd.h:21
GRFFilePropsBase::spritegroup
std::array< const struct SpriteGroup *, Tcnt > spritegroup
pointers to the different sprites of the entity
Definition: newgrf_commons.h:313
AirportSpec::Get
static const AirportSpec * Get(uint8_t type)
Retrieve airport spec for the given airport.
Definition: newgrf_airport.cpp:55
FLYING
@ FLYING
Vehicle is flying in the air.
Definition: airport.h:75
CmdRenameStation
CommandCost CmdRenameStation(DoCommandFlag flags, StationID station_id, const std::string &text)
Rename a station.
Definition: station_cmd.cpp:4326
FindDockLandPart
static TileIndex FindDockLandPart(TileIndex t)
Find the part of a dock that is land-based.
Definition: station_cmd.cpp:2930
newgrf_railtype.h
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
vehiclelist_func.h
MakeDock
void MakeDock(Tile t, Owner o, StationID sid, DiagDirection d, WaterClass wc)
Make the given tile a dock tile.
Definition: station_map.h:831
timer_game_economy.h
IsDriveThroughStopTile
bool IsDriveThroughStopTile(Tile t)
Is tile t a drive through road stop station or waypoint?
Definition: station_map.h:276
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:5166
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
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:589
AT_OILRIG
@ AT_OILRIG
Oilrig airport.
Definition: airport.h:38
StationNameInformation
Information to handle station action 0 property 24 correctly.
Definition: station_cmd.cpp:225
RailBuildCost
Money RailBuildCost(RailType railtype)
Returns the cost of building the specified railtype.
Definition: rail.h:375
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
Map::SizeY
static uint SizeY()
Get the size of the map along the Y.
Definition: map_func.h:279
WC_VEHICLE_ORDERS
@ WC_VEHICLE_ORDERS
Vehicle orders; Window numbers:
Definition: window_type.h:212
ClientSettings::gui
GUISettings gui
settings related to the GUI
Definition: settings_type.h:611
StationSpec::tileflags
std::vector< TileFlags > tileflags
List of tile flags.
Definition: newgrf_station.h:169
station_widget.h
debug.h
GetTrainForReservation
Train * GetTrainForReservation(TileIndex tile, Track track)
Find the train which has reserved a specific path.
Definition: pbs.cpp:330
Vehicle::refit_cap
uint16_t refit_cap
Capacity left over from before last refit.
Definition: vehicle_base.h:345
TileLayoutSpriteGroup
Action 2 sprite layout for houses, industry tiles, objects and airport tiles.
Definition: newgrf_spritegroup.h:260
MakeOilrig
void MakeOilrig(Tile t, StationID sid, WaterClass wc)
Make the given tile an oilrig tile.
Definition: station_map.h:843
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:735
GRFConfig::GetName
const char * GetName() const
Get the name of this grf.
Definition: newgrf_config.cpp:98
GoodsEntry::GES_LAST_MONTH
@ GES_LAST_MONTH
Set when cargo was delivered for final delivery last month.
Definition: station_base.h:195
UpdateStationAcceptance
void UpdateStationAcceptance(Station *st, bool show_msg)
Update the acceptance for a station.
Definition: station_cmd.cpp:625
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
BaseStation::speclist
std::vector< SpecMapping< StationSpec > > speclist
List of rail station specs of this station.
Definition: base_station_base.h:72
AirportTileSpec::animation
AnimationInfo animation
Information about the animation.
Definition: newgrf_airporttiles.h:69
news_func.h
RoadStopClassID
RoadStopClassID
Definition: newgrf_roadstop.h:28
roadveh.h
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
BaseStation::build_date
TimerGameCalendar::Date build_date
Date of construction.
Definition: base_station_base.h:75
FACIL_AIRPORT
@ FACIL_AIRPORT
Station with an airport.
Definition: station_type.h:57
EXPENSES_CONSTRUCTION
@ EXPENSES_CONSTRUCTION
Construction costs.
Definition: economy_type.h:173
GetCustomStationSpecIndex
uint GetCustomStationSpecIndex(Tile t)
Get the custom station spec for this tile.
Definition: station_map.h:635
TimerGameEconomy::date
static Date date
Current date in days (day counter).
Definition: timer_game_economy.h:37
FindFirstBit
constexpr uint8_t FindFirstBit(T x)
Search the first set bit in a value.
Definition: bitmath_func.hpp:213
HasBit
constexpr debug_inline bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
Definition: bitmath_func.hpp:103
INDUSTRYLIFE_EXTRACTIVE
@ INDUSTRYLIFE_EXTRACTIVE
Like mines.
Definition: industrytype.h:24