00001
00002
00003
00004
00005
00006
00007
00008
00009
00012 #include "stdafx.h"
00013 #include "aircraft.h"
00014 #include "bridge_map.h"
00015 #include "cmd_helper.h"
00016 #include "viewport_func.h"
00017 #include "command_func.h"
00018 #include "town.h"
00019 #include "news_func.h"
00020 #include "train.h"
00021 #include "ship.h"
00022 #include "roadveh.h"
00023 #include "industry.h"
00024 #include "newgrf_cargo.h"
00025 #include "newgrf_debug.h"
00026 #include "newgrf_station.h"
00027 #include "newgrf_canal.h"
00028 #include "pathfinder/yapf/yapf_cache.h"
00029 #include "road_internal.h"
00030 #include "autoslope.h"
00031 #include "water.h"
00032 #include "strings_func.h"
00033 #include "clear_func.h"
00034 #include "date_func.h"
00035 #include "vehicle_func.h"
00036 #include "string_func.h"
00037 #include "animated_tile_func.h"
00038 #include "elrail_func.h"
00039 #include "station_base.h"
00040 #include "roadstop_base.h"
00041 #include "newgrf_railtype.h"
00042 #include "waypoint_base.h"
00043 #include "waypoint_func.h"
00044 #include "pbs.h"
00045 #include "debug.h"
00046 #include "core/random_func.hpp"
00047 #include "company_base.h"
00048 #include "table/airporttile_ids.h"
00049 #include "newgrf_airporttiles.h"
00050 #include "order_backup.h"
00051 #include "newgrf_house.h"
00052 #include "company_gui.h"
00053 #include "linkgraph/linkgraph_base.h"
00054 #include "linkgraph/refresh.h"
00055 #include "widgets/station_widget.h"
00056
00057 #include "table/strings.h"
00058
00065 bool IsHangar(TileIndex t)
00066 {
00067 assert(IsTileType(t, MP_STATION));
00068
00069
00070 if (!IsAirport(t)) return false;
00071
00072 const Station *st = Station::GetByTile(t);
00073 const AirportSpec *as = st->airport.GetSpec();
00074
00075 for (uint i = 0; i < as->nof_depots; i++) {
00076 if (st->airport.GetHangarTile(i) == t) return true;
00077 }
00078
00079 return false;
00080 }
00081
00089 template <class T>
00090 CommandCost GetStationAround(TileArea ta, StationID closest_station, T **st)
00091 {
00092 ta.tile -= TileDiffXY(1, 1);
00093 ta.w += 2;
00094 ta.h += 2;
00095
00096
00097 TILE_AREA_LOOP(tile_cur, ta) {
00098 if (IsTileType(tile_cur, MP_STATION)) {
00099 StationID t = GetStationIndex(tile_cur);
00100 if (!T::IsValidID(t)) continue;
00101
00102 if (closest_station == INVALID_STATION) {
00103 closest_station = t;
00104 } else if (closest_station != t) {
00105 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
00106 }
00107 }
00108 }
00109 *st = (closest_station == INVALID_STATION) ? NULL : T::Get(closest_station);
00110 return CommandCost();
00111 }
00112
00118 typedef bool (*CMSAMatcher)(TileIndex tile);
00119
00126 static int CountMapSquareAround(TileIndex tile, CMSAMatcher cmp)
00127 {
00128 int num = 0;
00129
00130 for (int dx = -3; dx <= 3; dx++) {
00131 for (int dy = -3; dy <= 3; dy++) {
00132 TileIndex t = TileAddWrap(tile, dx, dy);
00133 if (t != INVALID_TILE && cmp(t)) num++;
00134 }
00135 }
00136
00137 return num;
00138 }
00139
00145 static bool CMSAMine(TileIndex tile)
00146 {
00147
00148 if (!IsTileType(tile, MP_INDUSTRY)) return false;
00149
00150 const Industry *ind = Industry::GetByTile(tile);
00151
00152
00153 if ((GetIndustrySpec(ind->type)->life_type & INDUSTRYLIFE_EXTRACTIVE) == 0) return false;
00154
00155 for (uint i = 0; i < lengthof(ind->produced_cargo); i++) {
00156
00157
00158 if (ind->produced_cargo[i] != CT_INVALID &&
00159 (CargoSpec::Get(ind->produced_cargo[i])->classes & (CC_LIQUID | CC_PASSENGERS | CC_MAIL)) == 0) {
00160 return true;
00161 }
00162 }
00163
00164 return false;
00165 }
00166
00172 static bool CMSAWater(TileIndex tile)
00173 {
00174 return IsTileType(tile, MP_WATER) && IsWater(tile);
00175 }
00176
00182 static bool CMSATree(TileIndex tile)
00183 {
00184 return IsTileType(tile, MP_TREES);
00185 }
00186
00187 #define M(x) ((x) - STR_SV_STNAME)
00188
00189 enum StationNaming {
00190 STATIONNAMING_RAIL,
00191 STATIONNAMING_ROAD,
00192 STATIONNAMING_AIRPORT,
00193 STATIONNAMING_OILRIG,
00194 STATIONNAMING_DOCK,
00195 STATIONNAMING_HELIPORT,
00196 };
00197
00199 struct StationNameInformation {
00200 uint32 free_names;
00201 bool *indtypes;
00202 };
00203
00212 static bool FindNearIndustryName(TileIndex tile, void *user_data)
00213 {
00214
00215 StationNameInformation *sni = (StationNameInformation*)user_data;
00216 if (!IsTileType(tile, MP_INDUSTRY)) return false;
00217
00218
00219 IndustryType indtype = GetIndustryType(tile);
00220 if (GetIndustrySpec(indtype)->station_name == STR_UNDEFINED) return false;
00221
00222
00223
00224 sni->free_names &= ~(1 << M(STR_SV_STNAME_OILFIELD) | 1 << M(STR_SV_STNAME_MINES));
00225 return !sni->indtypes[indtype];
00226 }
00227
00228 static StringID GenerateStationName(Station *st, TileIndex tile, StationNaming name_class)
00229 {
00230 static const uint32 _gen_station_name_bits[] = {
00231 0,
00232 0,
00233 1U << M(STR_SV_STNAME_AIRPORT),
00234 1U << M(STR_SV_STNAME_OILFIELD),
00235 1U << M(STR_SV_STNAME_DOCKS),
00236 1U << M(STR_SV_STNAME_HELIPORT),
00237 };
00238
00239 const Town *t = st->town;
00240 uint32 free_names = UINT32_MAX;
00241
00242 bool indtypes[NUM_INDUSTRYTYPES];
00243 memset(indtypes, 0, sizeof(indtypes));
00244
00245 const Station *s;
00246 FOR_ALL_STATIONS(s) {
00247 if (s != st && s->town == t) {
00248 if (s->indtype != IT_INVALID) {
00249 indtypes[s->indtype] = true;
00250 StringID name = GetIndustrySpec(s->indtype)->station_name;
00251 if (name != STR_UNDEFINED) {
00252
00253 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
00254 const IndustrySpec *indsp = GetIndustrySpec(it);
00255 if (indsp->enabled && indsp->station_name == name) indtypes[it] = true;
00256 }
00257 }
00258 continue;
00259 }
00260 uint str = M(s->string_id);
00261 if (str <= 0x20) {
00262 if (str == M(STR_SV_STNAME_FOREST)) {
00263 str = M(STR_SV_STNAME_WOODS);
00264 }
00265 ClrBit(free_names, str);
00266 }
00267 }
00268 }
00269
00270 TileIndex indtile = tile;
00271 StationNameInformation sni = { free_names, indtypes };
00272 if (CircularTileSearch(&indtile, 7, FindNearIndustryName, &sni)) {
00273
00274 IndustryType indtype = GetIndustryType(indtile);
00275 const IndustrySpec *indsp = GetIndustrySpec(indtype);
00276
00277 if (indsp->station_name != STR_NULL) {
00278 st->indtype = indtype;
00279 return STR_SV_STNAME_FALLBACK;
00280 }
00281 }
00282
00283
00284 free_names = sni.free_names;
00285
00286
00287 uint32 tmp = free_names & _gen_station_name_bits[name_class];
00288 if (tmp != 0) return STR_SV_STNAME + FindFirstBit(tmp);
00289
00290
00291 if (HasBit(free_names, M(STR_SV_STNAME_MINES))) {
00292 if (CountMapSquareAround(tile, CMSAMine) >= 2) {
00293 return STR_SV_STNAME_MINES;
00294 }
00295 }
00296
00297
00298 if (DistanceMax(tile, t->xy) < 8) {
00299 if (HasBit(free_names, M(STR_SV_STNAME))) return STR_SV_STNAME;
00300
00301 if (HasBit(free_names, M(STR_SV_STNAME_CENTRAL))) return STR_SV_STNAME_CENTRAL;
00302 }
00303
00304
00305 if (HasBit(free_names, M(STR_SV_STNAME_LAKESIDE)) &&
00306 DistanceFromEdge(tile) < 20 &&
00307 CountMapSquareAround(tile, CMSAWater) >= 5) {
00308 return STR_SV_STNAME_LAKESIDE;
00309 }
00310
00311
00312 if (HasBit(free_names, M(STR_SV_STNAME_WOODS)) && (
00313 CountMapSquareAround(tile, CMSATree) >= 8 ||
00314 CountMapSquareAround(tile, IsTileForestIndustry) >= 2)
00315 ) {
00316 return _settings_game.game_creation.landscape == LT_TROPIC ? STR_SV_STNAME_FOREST : STR_SV_STNAME_WOODS;
00317 }
00318
00319
00320 int z = GetTileZ(tile);
00321 int z2 = GetTileZ(t->xy);
00322 if (z < z2) {
00323 if (HasBit(free_names, M(STR_SV_STNAME_VALLEY))) return STR_SV_STNAME_VALLEY;
00324 } else if (z > z2) {
00325 if (HasBit(free_names, M(STR_SV_STNAME_HEIGHTS))) return STR_SV_STNAME_HEIGHTS;
00326 }
00327
00328
00329 static const int8 _direction_and_table[] = {
00330 ~( (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
00331 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
00332 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
00333 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) ),
00334 };
00335
00336 free_names &= _direction_and_table[
00337 (TileX(tile) < TileX(t->xy)) +
00338 (TileY(tile) < TileY(t->xy)) * 2];
00339
00340 tmp = free_names & ((1 << 1) | (1 << 2) | (1 << 3) | (1 << 4) | (1 << 6) | (1 << 7) | (1 << 12) | (1 << 26) | (1 << 27) | (1 << 28) | (1 << 29) | (1 << 30));
00341 return (tmp == 0) ? STR_SV_STNAME_FALLBACK : (STR_SV_STNAME + FindFirstBit(tmp));
00342 }
00343 #undef M
00344
00350 static Station *GetClosestDeletedStation(TileIndex tile)
00351 {
00352 uint threshold = 8;
00353 Station *best_station = NULL;
00354 Station *st;
00355
00356 FOR_ALL_STATIONS(st) {
00357 if (!st->IsInUse() && st->owner == _current_company) {
00358 uint cur_dist = DistanceManhattan(tile, st->xy);
00359
00360 if (cur_dist < threshold) {
00361 threshold = cur_dist;
00362 best_station = st;
00363 }
00364 }
00365 }
00366
00367 return best_station;
00368 }
00369
00370
00371 void Station::GetTileArea(TileArea *ta, StationType type) const
00372 {
00373 switch (type) {
00374 case STATION_RAIL:
00375 *ta = this->train_station;
00376 return;
00377
00378 case STATION_AIRPORT:
00379 *ta = this->airport;
00380 return;
00381
00382 case STATION_TRUCK:
00383 *ta = this->truck_station;
00384 return;
00385
00386 case STATION_BUS:
00387 *ta = this->bus_station;
00388 return;
00389
00390 case STATION_DOCK:
00391 case STATION_OILRIG:
00392 ta->tile = this->dock_tile;
00393 break;
00394
00395 default: NOT_REACHED();
00396 }
00397
00398 ta->w = 1;
00399 ta->h = 1;
00400 }
00401
00405 void Station::UpdateVirtCoord()
00406 {
00407 Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
00408
00409 pt.y -= 32 * ZOOM_LVL_BASE;
00410 if ((this->facilities & FACIL_AIRPORT) && this->airport.type == AT_OILRIG) pt.y -= 16 * ZOOM_LVL_BASE;
00411
00412 SetDParam(0, this->index);
00413 SetDParam(1, this->facilities);
00414 this->sign.UpdatePosition(pt.x, pt.y, STR_VIEWPORT_STATION);
00415
00416 SetWindowDirty(WC_STATION_VIEW, this->index);
00417 }
00418
00420 void UpdateAllStationVirtCoords()
00421 {
00422 BaseStation *st;
00423
00424 FOR_ALL_BASE_STATIONS(st) {
00425 st->UpdateVirtCoord();
00426 }
00427 }
00428
00434 static uint GetAcceptanceMask(const Station *st)
00435 {
00436 uint mask = 0;
00437
00438 for (CargoID i = 0; i < NUM_CARGO; i++) {
00439 if (HasBit(st->goods[i].acceptance_pickup, GoodsEntry::GES_ACCEPTANCE)) mask |= 1 << i;
00440 }
00441 return mask;
00442 }
00443
00448 static void ShowRejectOrAcceptNews(const Station *st, uint num_items, CargoID *cargo, StringID msg)
00449 {
00450 for (uint i = 0; i < num_items; i++) {
00451 SetDParam(i + 1, CargoSpec::Get(cargo[i])->name);
00452 }
00453
00454 SetDParam(0, st->index);
00455 AddNewsItem(msg, NT_ACCEPTANCE, NF_INCOLOUR | NF_SMALL, NR_STATION, st->index);
00456 }
00457
00465 CargoArray GetProductionAroundTiles(TileIndex tile, int w, int h, int rad)
00466 {
00467 CargoArray produced;
00468
00469 int x = TileX(tile);
00470 int y = TileY(tile);
00471
00472
00473
00474 int x2 = min(x + w + rad, MapSizeX());
00475 int x1 = max(x - rad, 0);
00476
00477 int y2 = min(y + h + rad, MapSizeY());
00478 int y1 = max(y - rad, 0);
00479
00480 assert(x1 < x2);
00481 assert(y1 < y2);
00482 assert(w > 0);
00483 assert(h > 0);
00484
00485 TileArea ta(TileXY(x1, y1), TileXY(x2 - 1, y2 - 1));
00486
00487
00488
00489 TILE_AREA_LOOP(tile, ta) AddProducedCargo(tile, produced);
00490
00491
00492
00493
00494
00495
00496
00497 const Industry *i;
00498 FOR_ALL_INDUSTRIES(i) {
00499 if (!ta.Intersects(i->location)) continue;
00500
00501 for (uint j = 0; j < lengthof(i->produced_cargo); j++) {
00502 CargoID cargo = i->produced_cargo[j];
00503 if (cargo != CT_INVALID) produced[cargo]++;
00504 }
00505 }
00506
00507 return produced;
00508 }
00509
00518 CargoArray GetAcceptanceAroundTiles(TileIndex tile, int w, int h, int rad, uint32 *always_accepted)
00519 {
00520 CargoArray acceptance;
00521 if (always_accepted != NULL) *always_accepted = 0;
00522
00523 int x = TileX(tile);
00524 int y = TileY(tile);
00525
00526
00527
00528 int x2 = min(x + w + rad, MapSizeX());
00529 int y2 = min(y + h + rad, MapSizeY());
00530 int x1 = max(x - rad, 0);
00531 int y1 = max(y - rad, 0);
00532
00533 assert(x1 < x2);
00534 assert(y1 < y2);
00535 assert(w > 0);
00536 assert(h > 0);
00537
00538 for (int yc = y1; yc != y2; yc++) {
00539 for (int xc = x1; xc != x2; xc++) {
00540 TileIndex tile = TileXY(xc, yc);
00541 AddAcceptedCargo(tile, acceptance, always_accepted);
00542 }
00543 }
00544
00545 return acceptance;
00546 }
00547
00553 void UpdateStationAcceptance(Station *st, bool show_msg)
00554 {
00555
00556 uint old_acc = GetAcceptanceMask(st);
00557
00558
00559 CargoArray acceptance;
00560 if (!st->rect.IsEmpty()) {
00561 acceptance = GetAcceptanceAroundTiles(
00562 TileXY(st->rect.left, st->rect.top),
00563 st->rect.right - st->rect.left + 1,
00564 st->rect.bottom - st->rect.top + 1,
00565 st->GetCatchmentRadius(),
00566 &st->always_accepted
00567 );
00568 }
00569
00570
00571 for (CargoID i = 0; i < NUM_CARGO; i++) {
00572 uint amt = acceptance[i];
00573
00574
00575 bool is_passengers = IsCargoInClass(i, CC_PASSENGERS);
00576 if ((!is_passengers && !(st->facilities & ~FACIL_BUS_STOP)) ||
00577 (is_passengers && !(st->facilities & ~FACIL_TRUCK_STOP))) {
00578 amt = 0;
00579 }
00580
00581 GoodsEntry &ge = st->goods[i];
00582 SB(ge.acceptance_pickup, GoodsEntry::GES_ACCEPTANCE, 1, amt >= 8);
00583 if (LinkGraph::IsValidID(ge.link_graph)) {
00584 (*LinkGraph::Get(ge.link_graph))[ge.node].SetDemand(amt / 8);
00585 }
00586 }
00587
00588
00589 uint new_acc = GetAcceptanceMask(st);
00590 if (old_acc == new_acc) return;
00591
00592
00593 if (show_msg && st->owner == _local_company && st->IsInUse()) {
00594
00595
00596 static const StringID accept_msg[] = {
00597 STR_NEWS_STATION_NOW_ACCEPTS_CARGO,
00598 STR_NEWS_STATION_NOW_ACCEPTS_CARGO_AND_CARGO,
00599 };
00600 static const StringID reject_msg[] = {
00601 STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO,
00602 STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO_OR_CARGO,
00603 };
00604
00605
00606 CargoID accepts[2] = { CT_INVALID, CT_INVALID };
00607 CargoID rejects[2] = { CT_INVALID, CT_INVALID };
00608 uint num_acc = 0;
00609 uint num_rej = 0;
00610
00611
00612 for (CargoID i = 0; i < NUM_CARGO; i++) {
00613 if (HasBit(new_acc, i)) {
00614 if (!HasBit(old_acc, i) && num_acc < lengthof(accepts)) {
00615
00616 accepts[num_acc++] = i;
00617 }
00618 } else {
00619 if (HasBit(old_acc, i) && num_rej < lengthof(rejects)) {
00620
00621 rejects[num_rej++] = i;
00622 }
00623 }
00624 }
00625
00626
00627 if (num_acc > 0) ShowRejectOrAcceptNews(st, num_acc, accepts, accept_msg[num_acc - 1]);
00628 if (num_rej > 0) ShowRejectOrAcceptNews(st, num_rej, rejects, reject_msg[num_rej - 1]);
00629 }
00630
00631
00632 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ACCEPT_RATING_LIST);
00633 }
00634
00635 static void UpdateStationSignCoord(BaseStation *st)
00636 {
00637 const StationRect *r = &st->rect;
00638
00639 if (r->IsEmpty()) return;
00640
00641
00642 st->xy = TileXY(ClampU(TileX(st->xy), r->left, r->right), ClampU(TileY(st->xy), r->top, r->bottom));
00643 st->UpdateVirtCoord();
00644 }
00645
00655 static CommandCost BuildStationPart(Station **st, DoCommandFlag flags, bool reuse, TileArea area, StationNaming name_class)
00656 {
00657
00658 if (*st == NULL && reuse) *st = GetClosestDeletedStation(area.tile);
00659
00660 if (*st != NULL) {
00661 if ((*st)->owner != _current_company) {
00662 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
00663 }
00664
00665 CommandCost ret = (*st)->rect.BeforeAddRect(area.tile, area.w, area.h, StationRect::ADD_TEST);
00666 if (ret.Failed()) return ret;
00667 } else {
00668
00669 if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
00670
00671 if (flags & DC_EXEC) {
00672 *st = new Station(area.tile);
00673
00674 (*st)->town = ClosestTownFromTile(area.tile, UINT_MAX);
00675 (*st)->string_id = GenerateStationName(*st, area.tile, name_class);
00676
00677 if (Company::IsValidID(_current_company)) {
00678 SetBit((*st)->town->have_ratings, _current_company);
00679 }
00680 }
00681 }
00682 return CommandCost();
00683 }
00684
00691 static void DeleteStationIfEmpty(BaseStation *st)
00692 {
00693 if (!st->IsInUse()) {
00694 st->delete_ctr = 0;
00695 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
00696 }
00697
00698 UpdateStationSignCoord(st);
00699 }
00700
00701 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags);
00702
00712 CommandCost CheckBuildableTile(TileIndex tile, uint invalid_dirs, int &allowed_z, bool allow_steep, bool check_bridge = true)
00713 {
00714 if (check_bridge && MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) {
00715 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00716 }
00717
00718 CommandCost ret = EnsureNoVehicleOnGround(tile);
00719 if (ret.Failed()) return ret;
00720
00721 int z;
00722 Slope tileh = GetTileSlope(tile, &z);
00723
00724
00725
00726
00727
00728 if ((!allow_steep && IsSteepSlope(tileh)) ||
00729 ((!_settings_game.construction.build_on_slopes) && tileh != SLOPE_FLAT)) {
00730 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00731 }
00732
00733 CommandCost cost(EXPENSES_CONSTRUCTION);
00734 int flat_z = z + GetSlopeMaxZ(tileh);
00735 if (tileh != SLOPE_FLAT) {
00736
00737 for (DiagDirection dir = DIAGDIR_BEGIN; dir != DIAGDIR_END; dir++) {
00738 if (HasBit(invalid_dirs, dir) && !CanBuildDepotByTileh(dir, tileh)) {
00739 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00740 }
00741 }
00742 cost.AddCost(_price[PR_BUILD_FOUNDATION]);
00743 }
00744
00745
00746 if (allowed_z < 0) {
00747
00748 allowed_z = flat_z;
00749 } else if (allowed_z != flat_z) {
00750 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00751 }
00752
00753 return cost;
00754 }
00755
00762 CommandCost CheckFlatLand(TileArea tile_area, DoCommandFlag flags)
00763 {
00764 CommandCost cost(EXPENSES_CONSTRUCTION);
00765 int allowed_z = -1;
00766
00767 TILE_AREA_LOOP(tile_cur, tile_area) {
00768 CommandCost ret = CheckBuildableTile(tile_cur, 0, allowed_z, true);
00769 if (ret.Failed()) return ret;
00770 cost.AddCost(ret);
00771
00772 ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00773 if (ret.Failed()) return ret;
00774 cost.AddCost(ret);
00775 }
00776
00777 return cost;
00778 }
00779
00794 static CommandCost CheckFlatLandRailStation(TileArea tile_area, DoCommandFlag flags, Axis axis, StationID *station, RailType rt, SmallVector<Train *, 4> &affected_vehicles, StationClassID spec_class, byte spec_index, byte plat_len, byte numtracks)
00795 {
00796 CommandCost cost(EXPENSES_CONSTRUCTION);
00797 int allowed_z = -1;
00798 uint invalid_dirs = 5 << axis;
00799
00800 const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
00801 bool slope_cb = statspec != NULL && HasBit(statspec->callback_mask, CBM_STATION_SLOPE_CHECK);
00802
00803 TILE_AREA_LOOP(tile_cur, tile_area) {
00804 CommandCost ret = CheckBuildableTile(tile_cur, invalid_dirs, allowed_z, false);
00805 if (ret.Failed()) return ret;
00806 cost.AddCost(ret);
00807
00808 if (slope_cb) {
00809
00810 ret = PerformStationTileSlopeCheck(tile_area.tile, tile_cur, statspec, axis, plat_len, numtracks);
00811 if (ret.Failed()) return ret;
00812 }
00813
00814
00815
00816
00817 if (station != NULL && IsTileType(tile_cur, MP_STATION)) {
00818 if (!IsRailStation(tile_cur)) {
00819 return ClearTile_Station(tile_cur, DC_AUTO);
00820 } else {
00821 StationID st = GetStationIndex(tile_cur);
00822 if (*station == INVALID_STATION) {
00823 *station = st;
00824 } else if (*station != st) {
00825 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
00826 }
00827 }
00828 } else {
00829
00830
00831 if (rt != INVALID_RAILTYPE &&
00832 IsPlainRailTile(tile_cur) && !HasSignals(tile_cur) &&
00833 HasPowerOnRail(GetRailType(tile_cur), rt)) {
00834
00835
00836
00837
00838
00839
00840 TrackBits tracks = GetTrackBits(tile_cur);
00841 Track track = RemoveFirstTrack(&tracks);
00842 Track expected_track = HasBit(invalid_dirs, DIAGDIR_NE) ? TRACK_X : TRACK_Y;
00843
00844 if (tracks == TRACK_BIT_NONE && track == expected_track) {
00845
00846 if (HasBit(GetRailReservationTrackBits(tile_cur), track)) {
00847 Train *v = GetTrainForReservation(tile_cur, track);
00848 if (v != NULL) {
00849 *affected_vehicles.Append() = v;
00850 }
00851 }
00852 CommandCost ret = DoCommand(tile_cur, 0, track, flags, CMD_REMOVE_SINGLE_RAIL);
00853 if (ret.Failed()) return ret;
00854 cost.AddCost(ret);
00855
00856 continue;
00857 }
00858 }
00859 ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00860 if (ret.Failed()) return ret;
00861 cost.AddCost(ret);
00862 }
00863 }
00864
00865 return cost;
00866 }
00867
00880 static CommandCost CheckFlatLandRoadStop(TileArea tile_area, DoCommandFlag flags, uint invalid_dirs, bool is_drive_through, bool is_truck_stop, Axis axis, StationID *station, RoadTypes rts)
00881 {
00882 CommandCost cost(EXPENSES_CONSTRUCTION);
00883 int allowed_z = -1;
00884
00885 TILE_AREA_LOOP(cur_tile, tile_area) {
00886 CommandCost ret = CheckBuildableTile(cur_tile, invalid_dirs, allowed_z, !is_drive_through);
00887 if (ret.Failed()) return ret;
00888 cost.AddCost(ret);
00889
00890
00891
00892
00893 if (station != NULL && IsTileType(cur_tile, MP_STATION)) {
00894 if (!IsRoadStop(cur_tile)) {
00895 return ClearTile_Station(cur_tile, DC_AUTO);
00896 } else {
00897 if (is_truck_stop != IsTruckStop(cur_tile) ||
00898 is_drive_through != IsDriveThroughStopTile(cur_tile)) {
00899 return ClearTile_Station(cur_tile, DC_AUTO);
00900 }
00901
00902 if (is_drive_through && IsDriveThroughStopTile(cur_tile) && DiagDirToAxis(GetRoadStopDir(cur_tile)) != axis){
00903 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
00904 }
00905 StationID st = GetStationIndex(cur_tile);
00906 if (*station == INVALID_STATION) {
00907 *station = st;
00908 } else if (*station != st) {
00909 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
00910 }
00911 }
00912 } else {
00913 bool build_over_road = is_drive_through && IsNormalRoadTile(cur_tile);
00914
00915 RoadBits rb = IsNormalRoadTile(cur_tile) ? GetAllRoadBits(cur_tile) : ROAD_NONE;
00916 if (build_over_road && (rb & (axis == AXIS_X ? ROAD_Y : ROAD_X)) != 0) {
00917
00918 switch (CountBits(rb)) {
00919 case 1:
00920 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
00921
00922 case 2:
00923 if (rb == ROAD_X || rb == ROAD_Y) return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
00924 return_cmd_error(STR_ERROR_DRIVE_THROUGH_CORNER);
00925
00926 default:
00927 return_cmd_error(STR_ERROR_DRIVE_THROUGH_JUNCTION);
00928 }
00929 }
00930
00931 RoadTypes cur_rts = IsNormalRoadTile(cur_tile) ? GetRoadTypes(cur_tile) : ROADTYPES_NONE;
00932 uint num_roadbits = 0;
00933 if (build_over_road) {
00934
00935 if (HasBit(cur_rts, ROADTYPE_ROAD)) {
00936 Owner road_owner = GetRoadOwner(cur_tile, ROADTYPE_ROAD);
00937 if (road_owner == OWNER_TOWN) {
00938 if (!_settings_game.construction.road_stop_on_town_road) return_cmd_error(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD);
00939 } else if (!_settings_game.construction.road_stop_on_competitor_road && road_owner != OWNER_NONE) {
00940 CommandCost ret = CheckOwnership(road_owner);
00941 if (ret.Failed()) return ret;
00942 }
00943 num_roadbits += CountBits(GetRoadBits(cur_tile, ROADTYPE_ROAD));
00944 }
00945
00946
00947 if (HasBit(cur_rts, ROADTYPE_TRAM)) {
00948 Owner tram_owner = GetRoadOwner(cur_tile, ROADTYPE_TRAM);
00949 if (!_settings_game.construction.road_stop_on_competitor_road && tram_owner != OWNER_NONE) {
00950 CommandCost ret = CheckOwnership(tram_owner);
00951 if (ret.Failed()) return ret;
00952 }
00953 num_roadbits += CountBits(GetRoadBits(cur_tile, ROADTYPE_TRAM));
00954 }
00955
00956
00957 rts |= cur_rts;
00958 } else {
00959 ret = DoCommand(cur_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00960 if (ret.Failed()) return ret;
00961 cost.AddCost(ret);
00962 }
00963
00964 uint roadbits_to_build = CountBits(rts) * 2 - num_roadbits;
00965 cost.AddCost(_price[PR_BUILD_ROAD] * roadbits_to_build);
00966 }
00967 }
00968
00969 return cost;
00970 }
00971
00979 CommandCost CanExpandRailStation(const BaseStation *st, TileArea &new_ta, Axis axis)
00980 {
00981 TileArea cur_ta = st->train_station;
00982
00983
00984 int x = min(TileX(cur_ta.tile), TileX(new_ta.tile));
00985 int y = min(TileY(cur_ta.tile), TileY(new_ta.tile));
00986 new_ta.w = max(TileX(cur_ta.tile) + cur_ta.w, TileX(new_ta.tile) + new_ta.w) - x;
00987 new_ta.h = max(TileY(cur_ta.tile) + cur_ta.h, TileY(new_ta.tile) + new_ta.h) - y;
00988 new_ta.tile = TileXY(x, y);
00989
00990
00991 if (new_ta.w > _settings_game.station.station_spread || new_ta.h > _settings_game.station.station_spread) {
00992 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
00993 }
00994
00995 return CommandCost();
00996 }
00997
00998 static inline byte *CreateSingle(byte *layout, int n)
00999 {
01000 int i = n;
01001 do *layout++ = 0; while (--i);
01002 layout[((n - 1) >> 1) - n] = 2;
01003 return layout;
01004 }
01005
01006 static inline byte *CreateMulti(byte *layout, int n, byte b)
01007 {
01008 int i = n;
01009 do *layout++ = b; while (--i);
01010 if (n > 4) {
01011 layout[0 - n] = 0;
01012 layout[n - 1 - n] = 0;
01013 }
01014 return layout;
01015 }
01016
01024 void GetStationLayout(byte *layout, int numtracks, int plat_len, const StationSpec *statspec)
01025 {
01026 if (statspec != NULL && statspec->lengths >= plat_len &&
01027 statspec->platforms[plat_len - 1] >= numtracks &&
01028 statspec->layouts[plat_len - 1][numtracks - 1]) {
01029
01030 memcpy(layout, statspec->layouts[plat_len - 1][numtracks - 1],
01031 plat_len * numtracks);
01032 return;
01033 }
01034
01035 if (plat_len == 1) {
01036 CreateSingle(layout, numtracks);
01037 } else {
01038 if (numtracks & 1) layout = CreateSingle(layout, plat_len);
01039 numtracks >>= 1;
01040
01041 while (--numtracks >= 0) {
01042 layout = CreateMulti(layout, plat_len, 4);
01043 layout = CreateMulti(layout, plat_len, 6);
01044 }
01045 }
01046 }
01047
01059 template <class T, StringID error_message>
01060 CommandCost FindJoiningBaseStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, T **st)
01061 {
01062 assert(*st == NULL);
01063 bool check_surrounding = true;
01064
01065 if (_settings_game.station.adjacent_stations) {
01066 if (existing_station != INVALID_STATION) {
01067 if (adjacent && existing_station != station_to_join) {
01068
01069
01070 return_cmd_error(error_message);
01071 } else {
01072
01073
01074 *st = T::GetIfValid(existing_station);
01075 check_surrounding = (*st == NULL);
01076 }
01077 } else {
01078
01079
01080 if (adjacent) check_surrounding = false;
01081 }
01082 }
01083
01084 if (check_surrounding) {
01085
01086 CommandCost ret = GetStationAround(ta, existing_station, st);
01087 if (ret.Failed()) return ret;
01088 }
01089
01090
01091 if (*st == NULL && station_to_join != INVALID_STATION) *st = T::GetIfValid(station_to_join);
01092
01093 return CommandCost();
01094 }
01095
01105 static CommandCost FindJoiningStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
01106 {
01107 return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_RAILWAY_STATION_FIRST>(existing_station, station_to_join, adjacent, ta, st);
01108 }
01109
01119 CommandCost FindJoiningWaypoint(StationID existing_waypoint, StationID waypoint_to_join, bool adjacent, TileArea ta, Waypoint **wp)
01120 {
01121 return FindJoiningBaseStation<Waypoint, STR_ERROR_MUST_REMOVE_RAILWAYPOINT_FIRST>(existing_waypoint, waypoint_to_join, adjacent, ta, wp);
01122 }
01123
01141 CommandCost CmdBuildRailStation(TileIndex tile_org, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01142 {
01143
01144 RailType rt = Extract<RailType, 0, 4>(p1);
01145 Axis axis = Extract<Axis, 4, 1>(p1);
01146 byte numtracks = GB(p1, 8, 8);
01147 byte plat_len = GB(p1, 16, 8);
01148 bool adjacent = HasBit(p1, 24);
01149
01150 StationClassID spec_class = Extract<StationClassID, 0, 8>(p2);
01151 byte spec_index = GB(p2, 8, 8);
01152 StationID station_to_join = GB(p2, 16, 16);
01153
01154
01155 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile_org, flags);
01156 if (ret.Failed()) return ret;
01157
01158 if (!ValParamRailtype(rt)) return CMD_ERROR;
01159
01160
01161 if ((uint)spec_class >= StationClass::GetClassCount() || spec_class == STAT_CLASS_WAYP) return CMD_ERROR;
01162 if (spec_index >= StationClass::Get(spec_class)->GetSpecCount()) return CMD_ERROR;
01163 if (plat_len == 0 || numtracks == 0) return CMD_ERROR;
01164
01165 int w_org, h_org;
01166 if (axis == AXIS_X) {
01167 w_org = plat_len;
01168 h_org = numtracks;
01169 } else {
01170 h_org = plat_len;
01171 w_org = numtracks;
01172 }
01173
01174 bool reuse = (station_to_join != NEW_STATION);
01175 if (!reuse) station_to_join = INVALID_STATION;
01176 bool distant_join = (station_to_join != INVALID_STATION);
01177
01178 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
01179
01180 if (h_org > _settings_game.station.station_spread || w_org > _settings_game.station.station_spread) return CMD_ERROR;
01181
01182
01183 TileArea new_location(tile_org, w_org, h_org);
01184
01185
01186 StationID est = INVALID_STATION;
01187 SmallVector<Train *, 4> affected_vehicles;
01188
01189 CommandCost cost = CheckFlatLandRailStation(new_location, flags, axis, &est, rt, affected_vehicles, spec_class, spec_index, plat_len, numtracks);
01190 if (cost.Failed()) return cost;
01191
01192 cost.AddCost((numtracks * _price[PR_BUILD_STATION_RAIL] + _price[PR_BUILD_STATION_RAIL_LENGTH]) * plat_len);
01193 cost.AddCost(numtracks * plat_len * RailBuildCost(rt));
01194
01195 Station *st = NULL;
01196 ret = FindJoiningStation(est, station_to_join, adjacent, new_location, &st);
01197 if (ret.Failed()) return ret;
01198
01199 ret = BuildStationPart(&st, flags, reuse, new_location, STATIONNAMING_RAIL);
01200 if (ret.Failed()) return ret;
01201
01202 if (st != NULL && st->train_station.tile != INVALID_TILE) {
01203 CommandCost ret = CanExpandRailStation(st, new_location, axis);
01204 if (ret.Failed()) return ret;
01205 }
01206
01207
01208 const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
01209 int specindex = AllocateSpecToStation(statspec, st, (flags & DC_EXEC) != 0);
01210 if (specindex == -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS);
01211
01212 if (statspec != NULL) {
01213
01214
01215
01216 if (HasBit(statspec->disallowed_platforms, numtracks - 1) || HasBit(statspec->disallowed_lengths, plat_len - 1)) {
01217 return CMD_ERROR;
01218 }
01219
01220
01221 if (HasBit(statspec->callback_mask, CBM_STATION_AVAIL)) {
01222 uint16 cb_res = GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, NULL, INVALID_TILE);
01223 if (cb_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(statspec->grf_prop.grffile, CBID_STATION_AVAILABILITY, cb_res)) return CMD_ERROR;
01224 }
01225 }
01226
01227 if (flags & DC_EXEC) {
01228 TileIndexDiff tile_delta;
01229 byte *layout_ptr;
01230 byte numtracks_orig;
01231 Track track;
01232
01233 st->train_station = new_location;
01234 st->AddFacility(FACIL_TRAIN, new_location.tile);
01235
01236 st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TRY);
01237
01238 if (statspec != NULL) {
01239
01240
01241 st->cached_anim_triggers |= statspec->animation.triggers;
01242 }
01243
01244 tile_delta = (axis == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
01245 track = AxisToTrack(axis);
01246
01247 layout_ptr = AllocaM(byte, numtracks * plat_len);
01248 GetStationLayout(layout_ptr, numtracks, plat_len, statspec);
01249
01250 numtracks_orig = numtracks;
01251
01252 Company *c = Company::Get(st->owner);
01253 TileIndex tile_track = tile_org;
01254 do {
01255 TileIndex tile = tile_track;
01256 int w = plat_len;
01257 do {
01258 byte layout = *layout_ptr++;
01259 if (IsRailStationTile(tile) && HasStationReservation(tile)) {
01260
01261 Train *v = GetTrainForReservation(tile, AxisToTrack(GetRailStationAxis(tile)));
01262 if (v != NULL) {
01263 FreeTrainTrackReservation(v);
01264 *affected_vehicles.Append() = v;
01265 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
01266 for (; v->Next() != NULL; v = v->Next()) { }
01267 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), false);
01268 }
01269 }
01270
01271
01272 if (IsRailStationTile(tile)) {
01273 if (!IsStationTileBlocked(tile)) c->infrastructure.rail[GetRailType(tile)]--;
01274 c->infrastructure.station--;
01275 }
01276
01277
01278 DeleteAnimatedTile(tile);
01279 byte old_specindex = HasStationTileRail(tile) ? GetCustomStationSpecIndex(tile) : 0;
01280 MakeRailStation(tile, st->owner, st->index, axis, layout & ~1, rt);
01281
01282 DeallocateSpecFromStation(st, old_specindex);
01283
01284 SetCustomStationSpecIndex(tile, specindex);
01285 SetStationTileRandomBits(tile, GB(Random(), 0, 4));
01286 SetAnimationFrame(tile, 0);
01287
01288 if (!IsStationTileBlocked(tile)) c->infrastructure.rail[rt]++;
01289 c->infrastructure.station++;
01290
01291 if (statspec != NULL) {
01292
01293 uint32 platinfo = GetPlatformInfo(AXIS_X, GetStationGfx(tile), plat_len, numtracks_orig, plat_len - w, numtracks_orig - numtracks, false);
01294
01295
01296 uint16 callback = GetStationCallback(CBID_STATION_TILE_LAYOUT, platinfo, 0, statspec, NULL, tile);
01297 if (callback != CALLBACK_FAILED) {
01298 if (callback < 8) {
01299 SetStationGfx(tile, (callback & ~1) + axis);
01300 } else {
01301 ErrorUnknownCallbackResult(statspec->grf_prop.grffile->grfid, CBID_STATION_TILE_LAYOUT, callback);
01302 }
01303 }
01304
01305
01306 TriggerStationAnimation(st, tile, SAT_BUILT);
01307 }
01308
01309 tile += tile_delta;
01310 } while (--w);
01311 AddTrackToSignalBuffer(tile_track, track, _current_company);
01312 YapfNotifyTrackLayoutChange(tile_track, track);
01313 tile_track += tile_delta ^ TileDiffXY(1, 1);
01314 } while (--numtracks);
01315
01316 for (uint i = 0; i < affected_vehicles.Length(); ++i) {
01317
01318 Train *v = affected_vehicles[i];
01319 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
01320 TryPathReserve(v, true, true);
01321 for (; v->Next() != NULL; v = v->Next()) { }
01322 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
01323 }
01324
01325
01326 TileArea update_reservation_area;
01327 if (axis == AXIS_X) {
01328 update_reservation_area = TileArea(tile_org, 1, numtracks_orig);
01329 } else {
01330 update_reservation_area = TileArea(tile_org, numtracks_orig, 1);
01331 }
01332
01333 TILE_AREA_LOOP(tile, update_reservation_area) {
01334
01335 if (IsStationTileBlocked(tile)) continue;
01336
01337 DiagDirection dir = AxisToDiagDir(axis);
01338 TileIndexDiff tile_offset = TileOffsByDiagDir(dir);
01339 TileIndex platform_begin = tile;
01340 TileIndex platform_end = tile;
01341
01342
01343 for (TileIndex next_tile = platform_begin - tile_offset; IsCompatibleTrainStationTile(next_tile, platform_begin); next_tile -= tile_offset) {
01344 platform_begin = next_tile;
01345 }
01346 for (TileIndex next_tile = platform_end + tile_offset; IsCompatibleTrainStationTile(next_tile, platform_end); next_tile += tile_offset) {
01347 platform_end = next_tile;
01348 }
01349
01350
01351 bool reservation = false;
01352 for (TileIndex t = platform_begin; !reservation && t <= platform_end; t += tile_offset) {
01353 reservation = HasStationReservation(t);
01354 }
01355
01356 if (reservation) {
01357 SetRailStationPlatformReservation(platform_begin, dir, true);
01358 }
01359 }
01360
01361 st->MarkTilesDirty(false);
01362 st->UpdateVirtCoord();
01363 UpdateStationAcceptance(st, false);
01364 st->RecomputeIndustriesNear();
01365 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
01366 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
01367 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
01368 DirtyCompanyInfrastructureWindows(st->owner);
01369 }
01370
01371 return cost;
01372 }
01373
01374 static void MakeRailStationAreaSmaller(BaseStation *st)
01375 {
01376 TileArea ta = st->train_station;
01377
01378 restart:
01379
01380
01381 if (ta.w != 0 && ta.h != 0) {
01382
01383 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(0, i));) {
01384
01385 if (++i == ta.h) {
01386 ta.tile += TileDiffXY(1, 0);
01387 ta.w--;
01388 goto restart;
01389 }
01390 }
01391
01392
01393 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(ta.w - 1, i));) {
01394
01395 if (++i == ta.h) {
01396 ta.w--;
01397 goto restart;
01398 }
01399 }
01400
01401
01402 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(i, 0));) {
01403
01404 if (++i == ta.w) {
01405 ta.tile += TileDiffXY(0, 1);
01406 ta.h--;
01407 goto restart;
01408 }
01409 }
01410
01411
01412 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(i, ta.h - 1));) {
01413
01414 if (++i == ta.w) {
01415 ta.h--;
01416 goto restart;
01417 }
01418 }
01419 } else {
01420 ta.Clear();
01421 }
01422
01423 st->train_station = ta;
01424 }
01425
01436 template <class T>
01437 CommandCost RemoveFromRailBaseStation(TileArea ta, SmallVector<T *, 4> &affected_stations, DoCommandFlag flags, Money removal_cost, bool keep_rail)
01438 {
01439
01440 int quantity = 0;
01441 CommandCost total_cost(EXPENSES_CONSTRUCTION);
01442
01443
01444
01445 CommandCost error;
01446
01447
01448 TILE_AREA_LOOP(tile, ta) {
01449
01450 if (!HasStationTileRail(tile)) continue;
01451
01452
01453 CommandCost ret = EnsureNoVehicleOnGround(tile);
01454 error.AddCost(ret);
01455 if (ret.Failed()) continue;
01456
01457
01458 T *st = T::GetByTile(tile);
01459 if (st == NULL) continue;
01460
01461 if (_current_company != OWNER_WATER) {
01462 CommandCost ret = CheckOwnership(st->owner);
01463 error.AddCost(ret);
01464 if (ret.Failed()) continue;
01465 }
01466
01467
01468 quantity++;
01469
01470 if (keep_rail || IsStationTileBlocked(tile)) {
01471
01472
01473 total_cost.AddCost(-_price[PR_CLEAR_RAIL]);
01474 }
01475
01476 if (flags & DC_EXEC) {
01477
01478 uint specindex = GetCustomStationSpecIndex(tile);
01479 Track track = GetRailStationTrack(tile);
01480 Owner owner = GetTileOwner(tile);
01481 RailType rt = GetRailType(tile);
01482 Train *v = NULL;
01483
01484 if (HasStationReservation(tile)) {
01485 v = GetTrainForReservation(tile, track);
01486 if (v != NULL) {
01487
01488 FreeTrainTrackReservation(v);
01489 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
01490 Vehicle *temp = v;
01491 for (; temp->Next() != NULL; temp = temp->Next()) { }
01492 if (IsRailStationTile(temp->tile)) SetRailStationPlatformReservation(temp->tile, TrackdirToExitdir(ReverseTrackdir(temp->GetVehicleTrackdir())), false);
01493 }
01494 }
01495
01496 bool build_rail = keep_rail && !IsStationTileBlocked(tile);
01497 if (!build_rail && !IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[rt]--;
01498
01499 DoClearSquare(tile);
01500 DeleteNewGRFInspectWindow(GSF_STATIONS, tile);
01501 if (build_rail) MakeRailNormal(tile, owner, TrackToTrackBits(track), rt);
01502 Company::Get(owner)->infrastructure.station--;
01503 DirtyCompanyInfrastructureWindows(owner);
01504
01505 st->rect.AfterRemoveTile(st, tile);
01506 AddTrackToSignalBuffer(tile, track, owner);
01507 YapfNotifyTrackLayoutChange(tile, track);
01508
01509 DeallocateSpecFromStation(st, specindex);
01510
01511 affected_stations.Include(st);
01512
01513 if (v != NULL) {
01514
01515 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
01516 TryPathReserve(v, true, true);
01517 for (; v->Next() != NULL; v = v->Next()) { }
01518 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
01519 }
01520 }
01521 }
01522
01523 if (quantity == 0) return error.Failed() ? error : CommandCost(STR_ERROR_THERE_IS_NO_STATION);
01524
01525 for (T **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
01526 T *st = *stp;
01527
01528
01529
01530
01531 MakeRailStationAreaSmaller(st);
01532 UpdateStationSignCoord(st);
01533
01534
01535 if (st->train_station.tile == INVALID_TILE) {
01536 st->facilities &= ~FACIL_TRAIN;
01537 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
01538 st->UpdateVirtCoord();
01539 DeleteStationIfEmpty(st);
01540 }
01541 }
01542
01543 total_cost.AddCost(quantity * removal_cost);
01544 return total_cost;
01545 }
01546
01558 CommandCost CmdRemoveFromRailStation(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01559 {
01560 TileIndex end = p1 == 0 ? start : p1;
01561 if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
01562
01563 TileArea ta(start, end);
01564 SmallVector<Station *, 4> affected_stations;
01565
01566 CommandCost ret = RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_STATION_RAIL], HasBit(p2, 0));
01567 if (ret.Failed()) return ret;
01568
01569
01570 for (Station **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
01571 Station *st = *stp;
01572
01573 if (st->train_station.tile == INVALID_TILE) SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
01574 st->MarkTilesDirty(false);
01575 st->RecomputeIndustriesNear();
01576 }
01577
01578
01579 return ret;
01580 }
01581
01593 CommandCost CmdRemoveFromRailWaypoint(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01594 {
01595 TileIndex end = p1 == 0 ? start : p1;
01596 if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
01597
01598 TileArea ta(start, end);
01599 SmallVector<Waypoint *, 4> affected_stations;
01600
01601 return RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_WAYPOINT_RAIL], HasBit(p2, 0));
01602 }
01603
01604
01612 template <class T>
01613 CommandCost RemoveRailStation(T *st, DoCommandFlag flags)
01614 {
01615
01616 if (_current_company != OWNER_WATER) {
01617 CommandCost ret = CheckOwnership(st->owner);
01618 if (ret.Failed()) return ret;
01619 }
01620
01621
01622 TileArea ta = st->train_station;
01623
01624 assert(ta.w != 0 && ta.h != 0);
01625
01626 CommandCost cost(EXPENSES_CONSTRUCTION);
01627
01628 TILE_AREA_LOOP(tile, ta) {
01629
01630 if (!st->TileBelongsToRailStation(tile)) continue;
01631
01632 CommandCost ret = EnsureNoVehicleOnGround(tile);
01633 if (ret.Failed()) return ret;
01634
01635 cost.AddCost(_price[PR_CLEAR_STATION_RAIL]);
01636 if (flags & DC_EXEC) {
01637
01638 Track track = GetRailStationTrack(tile);
01639 Owner owner = GetTileOwner(tile);
01640 Train *v = NULL;
01641 if (HasStationReservation(tile)) {
01642 v = GetTrainForReservation(tile, track);
01643 if (v != NULL) FreeTrainTrackReservation(v);
01644 }
01645 if (!IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[GetRailType(tile)]--;
01646 Company::Get(owner)->infrastructure.station--;
01647 DoClearSquare(tile);
01648 DeleteNewGRFInspectWindow(GSF_STATIONS, tile);
01649 AddTrackToSignalBuffer(tile, track, owner);
01650 YapfNotifyTrackLayoutChange(tile, track);
01651 if (v != NULL) TryPathReserve(v, true);
01652 }
01653 }
01654
01655 if (flags & DC_EXEC) {
01656 st->rect.AfterRemoveRect(st, st->train_station);
01657
01658 st->train_station.Clear();
01659
01660 st->facilities &= ~FACIL_TRAIN;
01661
01662 free(st->speclist);
01663 st->num_specs = 0;
01664 st->speclist = NULL;
01665 st->cached_anim_triggers = 0;
01666
01667 DirtyCompanyInfrastructureWindows(st->owner);
01668 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
01669 st->UpdateVirtCoord();
01670 DeleteStationIfEmpty(st);
01671 }
01672
01673 return cost;
01674 }
01675
01682 static CommandCost RemoveRailStation(TileIndex tile, DoCommandFlag flags)
01683 {
01684
01685 if (_current_company == OWNER_WATER) {
01686 return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_STATION);
01687 }
01688
01689 Station *st = Station::GetByTile(tile);
01690 CommandCost cost = RemoveRailStation(st, flags);
01691
01692 if (flags & DC_EXEC) st->RecomputeIndustriesNear();
01693
01694 return cost;
01695 }
01696
01703 static CommandCost RemoveRailWaypoint(TileIndex tile, DoCommandFlag flags)
01704 {
01705
01706 if (_current_company == OWNER_WATER) {
01707 return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_WAYPOINT);
01708 }
01709
01710 return RemoveRailStation(Waypoint::GetByTile(tile), flags);
01711 }
01712
01713
01719 static RoadStop **FindRoadStopSpot(bool truck_station, Station *st)
01720 {
01721 RoadStop **primary_stop = (truck_station) ? &st->truck_stops : &st->bus_stops;
01722
01723 if (*primary_stop == NULL) {
01724
01725 return primary_stop;
01726 } else {
01727
01728 RoadStop *stop = *primary_stop;
01729 while (stop->next != NULL) stop = stop->next;
01730 return &stop->next;
01731 }
01732 }
01733
01734 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags);
01735
01745 static CommandCost FindJoiningRoadStop(StationID existing_stop, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
01746 {
01747 return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST>(existing_stop, station_to_join, adjacent, ta, st);
01748 }
01749
01765 CommandCost CmdBuildRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01766 {
01767 bool type = HasBit(p2, 0);
01768 bool is_drive_through = HasBit(p2, 1);
01769 RoadTypes rts = Extract<RoadTypes, 2, 2>(p2);
01770 StationID station_to_join = GB(p2, 16, 16);
01771 bool reuse = (station_to_join != NEW_STATION);
01772 if (!reuse) station_to_join = INVALID_STATION;
01773 bool distant_join = (station_to_join != INVALID_STATION);
01774
01775 uint8 width = (uint8)GB(p1, 0, 8);
01776 uint8 lenght = (uint8)GB(p1, 8, 8);
01777
01778
01779 if (width > _settings_game.station.station_spread || lenght > _settings_game.station.station_spread) return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
01780
01781 if (width == 0 || lenght == 0) return CMD_ERROR;
01782
01783 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, lenght - 1) == INVALID_TILE) return CMD_ERROR;
01784
01785 TileArea roadstop_area(tile, width, lenght);
01786
01787 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
01788
01789 if (!HasExactlyOneBit(rts) || !HasRoadTypesAvail(_current_company, rts)) return CMD_ERROR;
01790
01791
01792 if (!is_drive_through && HasBit(rts, ROADTYPE_TRAM)) return CMD_ERROR;
01793
01794 DiagDirection ddir = Extract<DiagDirection, 6, 2>(p2);
01795
01796
01797 if (!IsValidDiagDirection(ddir)) return CMD_ERROR;
01798
01799 if (is_drive_through && !IsValidAxis((Axis)ddir)) return CMD_ERROR;
01800
01801 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
01802 if (ret.Failed()) return ret;
01803
01804
01805 CommandCost cost(EXPENSES_CONSTRUCTION, roadstop_area.w * roadstop_area.h * _price[type ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS]);
01806 StationID est = INVALID_STATION;
01807 ret = CheckFlatLandRoadStop(roadstop_area, flags, is_drive_through ? 5 << ddir : 1 << ddir, is_drive_through, type, DiagDirToAxis(ddir), &est, rts);
01808 if (ret.Failed()) return ret;
01809 cost.AddCost(ret);
01810
01811 Station *st = NULL;
01812 ret = FindJoiningRoadStop(est, station_to_join, HasBit(p2, 5), roadstop_area, &st);
01813 if (ret.Failed()) return ret;
01814
01815
01816 if (!RoadStop::CanAllocateItem(roadstop_area.w * roadstop_area.h)) return_cmd_error(type ? STR_ERROR_TOO_MANY_TRUCK_STOPS : STR_ERROR_TOO_MANY_BUS_STOPS);
01817
01818 ret = BuildStationPart(&st, flags, reuse, roadstop_area, STATIONNAMING_ROAD);
01819 if (ret.Failed()) return ret;
01820
01821 if (flags & DC_EXEC) {
01822
01823 TILE_AREA_LOOP(cur_tile, roadstop_area) {
01824 RoadTypes cur_rts = GetRoadTypes(cur_tile);
01825 Owner road_owner = HasBit(cur_rts, ROADTYPE_ROAD) ? GetRoadOwner(cur_tile, ROADTYPE_ROAD) : _current_company;
01826 Owner tram_owner = HasBit(cur_rts, ROADTYPE_TRAM) ? GetRoadOwner(cur_tile, ROADTYPE_TRAM) : _current_company;
01827
01828 if (IsTileType(cur_tile, MP_STATION) && IsRoadStop(cur_tile)) {
01829 RemoveRoadStop(cur_tile, flags);
01830 }
01831
01832 RoadStop *road_stop = new RoadStop(cur_tile);
01833
01834 RoadStop **currstop = FindRoadStopSpot(type, st);
01835 *currstop = road_stop;
01836
01837 if (type) {
01838 st->truck_station.Add(cur_tile);
01839 } else {
01840 st->bus_station.Add(cur_tile);
01841 }
01842
01843
01844 st->AddFacility((type) ? FACIL_TRUCK_STOP : FACIL_BUS_STOP, cur_tile);
01845
01846 st->rect.BeforeAddTile(cur_tile, StationRect::ADD_TRY);
01847
01848 RoadStopType rs_type = type ? ROADSTOP_TRUCK : ROADSTOP_BUS;
01849 if (is_drive_through) {
01850
01851
01852 RoadType rt;
01853 FOR_EACH_SET_ROADTYPE(rt, cur_rts | rts) {
01854 Company *c = Company::GetIfValid(rt == ROADTYPE_ROAD ? road_owner : tram_owner);
01855 if (c != NULL) {
01856 c->infrastructure.road[rt] += 2 - (IsNormalRoadTile(cur_tile) && HasBit(cur_rts, rt) ? CountBits(GetRoadBits(cur_tile, rt)) : 0);
01857 DirtyCompanyInfrastructureWindows(c->index);
01858 }
01859 }
01860
01861 MakeDriveThroughRoadStop(cur_tile, st->owner, road_owner, tram_owner, st->index, rs_type, rts | cur_rts, DiagDirToAxis(ddir));
01862 road_stop->MakeDriveThrough();
01863 } else {
01864
01865 Company::Get(st->owner)->infrastructure.road[FIND_FIRST_BIT(rts)] += 2;
01866 MakeRoadStop(cur_tile, st->owner, st->index, rs_type, rts, ddir);
01867 }
01868 Company::Get(st->owner)->infrastructure.station++;
01869 DirtyCompanyInfrastructureWindows(st->owner);
01870
01871 MarkTileDirtyByTile(cur_tile);
01872 }
01873 }
01874
01875 if (st != NULL) {
01876 st->UpdateVirtCoord();
01877 UpdateStationAcceptance(st, false);
01878 st->RecomputeIndustriesNear();
01879 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
01880 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
01881 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ROADVEHS);
01882 }
01883 return cost;
01884 }
01885
01886
01887 static Vehicle *ClearRoadStopStatusEnum(Vehicle *v, void *)
01888 {
01889 if (v->type == VEH_ROAD) {
01890
01891
01892
01893
01894
01895
01896 RoadVehicle *rv = RoadVehicle::From(v);
01897 if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) rv->state &= RVSB_ROAD_STOP_TRACKDIR_MASK;
01898 }
01899
01900 return NULL;
01901 }
01902
01903
01910 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags)
01911 {
01912 Station *st = Station::GetByTile(tile);
01913
01914 if (_current_company != OWNER_WATER) {
01915 CommandCost ret = CheckOwnership(st->owner);
01916 if (ret.Failed()) return ret;
01917 }
01918
01919 bool is_truck = IsTruckStop(tile);
01920
01921 RoadStop **primary_stop;
01922 RoadStop *cur_stop;
01923 if (is_truck) {
01924 primary_stop = &st->truck_stops;
01925 cur_stop = RoadStop::GetByTile(tile, ROADSTOP_TRUCK);
01926 } else {
01927 primary_stop = &st->bus_stops;
01928 cur_stop = RoadStop::GetByTile(tile, ROADSTOP_BUS);
01929 }
01930
01931 assert(cur_stop != NULL);
01932
01933
01934 if (IsDriveThroughStopTile(tile) && (flags & DC_BANKRUPT)) {
01935
01936 if (flags & DC_EXEC) FindVehicleOnPos(tile, NULL, &ClearRoadStopStatusEnum);
01937 } else {
01938 CommandCost ret = EnsureNoVehicleOnGround(tile);
01939 if (ret.Failed()) return ret;
01940 }
01941
01942 if (flags & DC_EXEC) {
01943 if (*primary_stop == cur_stop) {
01944
01945 *primary_stop = cur_stop->next;
01946
01947 if (*primary_stop == NULL) {
01948 st->facilities &= (is_truck ? ~FACIL_TRUCK_STOP : ~FACIL_BUS_STOP);
01949 }
01950 } else {
01951
01952 RoadStop *pred = *primary_stop;
01953 while (pred->next != cur_stop) pred = pred->next;
01954 pred->next = cur_stop->next;
01955 }
01956
01957
01958 RoadType rt;
01959 FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(tile)) {
01960 Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
01961 if (c != NULL) {
01962 c->infrastructure.road[rt] -= 2;
01963 DirtyCompanyInfrastructureWindows(c->index);
01964 }
01965 }
01966 Company::Get(st->owner)->infrastructure.station--;
01967
01968 if (IsDriveThroughStopTile(tile)) {
01969
01970 cur_stop->ClearDriveThrough();
01971 } else {
01972 DoClearSquare(tile);
01973 }
01974
01975 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ROADVEHS);
01976 delete cur_stop;
01977
01978
01979 RoadVehicle *v;
01980 FOR_ALL_ROADVEHICLES(v) {
01981 if (v->First() == v && v->current_order.IsType(OT_GOTO_STATION) &&
01982 v->dest_tile == tile) {
01983 v->dest_tile = v->GetOrderStationLocation(st->index);
01984 }
01985 }
01986
01987 st->rect.AfterRemoveTile(st, tile);
01988
01989 st->UpdateVirtCoord();
01990 st->RecomputeIndustriesNear();
01991 DeleteStationIfEmpty(st);
01992
01993
01994 if (is_truck) {
01995 st->truck_station.Clear();
01996 for (const RoadStop *rs = st->truck_stops; rs != NULL; rs = rs->next) st->truck_station.Add(rs->xy);
01997 } else {
01998 st->bus_station.Clear();
01999 for (const RoadStop *rs = st->bus_stops; rs != NULL; rs = rs->next) st->bus_station.Add(rs->xy);
02000 }
02001 }
02002
02003 return CommandCost(EXPENSES_CONSTRUCTION, _price[is_truck ? PR_CLEAR_STATION_TRUCK : PR_CLEAR_STATION_BUS]);
02004 }
02005
02016 CommandCost CmdRemoveRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02017 {
02018 uint8 width = (uint8)GB(p1, 0, 8);
02019 uint8 height = (uint8)GB(p1, 8, 8);
02020
02021
02022 if (width == 0 || height == 0) return CMD_ERROR;
02023
02024 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, height - 1) == INVALID_TILE) return CMD_ERROR;
02025
02026 TileArea roadstop_area(tile, width, height);
02027
02028 int quantity = 0;
02029 CommandCost cost(EXPENSES_CONSTRUCTION);
02030 TILE_AREA_LOOP(cur_tile, roadstop_area) {
02031
02032 if (!IsTileType(cur_tile, MP_STATION) || !IsRoadStop(cur_tile) || (uint32)GetRoadStopType(cur_tile) != GB(p2, 0, 1)) continue;
02033
02034
02035 bool is_drive_through = IsDriveThroughStopTile(cur_tile);
02036 RoadTypes rts = GetRoadTypes(cur_tile);
02037 RoadBits road_bits = IsDriveThroughStopTile(cur_tile) ?
02038 ((GetRoadStopDir(cur_tile) == DIAGDIR_NE) ? ROAD_X : ROAD_Y) :
02039 DiagDirToRoadBits(GetRoadStopDir(cur_tile));
02040
02041 Owner road_owner = GetRoadOwner(cur_tile, ROADTYPE_ROAD);
02042 Owner tram_owner = GetRoadOwner(cur_tile, ROADTYPE_TRAM);
02043 CommandCost ret = RemoveRoadStop(cur_tile, flags);
02044 if (ret.Failed()) return ret;
02045 cost.AddCost(ret);
02046
02047 quantity++;
02048
02049 if ((flags & DC_EXEC) && is_drive_through) {
02050 MakeRoadNormal(cur_tile, road_bits, rts, ClosestTownFromTile(cur_tile, UINT_MAX)->index,
02051 road_owner, tram_owner);
02052
02053
02054 RoadType rt;
02055 FOR_EACH_SET_ROADTYPE(rt, rts) {
02056 Company *c = Company::GetIfValid(GetRoadOwner(cur_tile, rt));
02057 if (c != NULL) {
02058 c->infrastructure.road[rt] += CountBits(road_bits);
02059 DirtyCompanyInfrastructureWindows(c->index);
02060 }
02061 }
02062 }
02063 }
02064
02065 if (quantity == 0) return_cmd_error(STR_ERROR_THERE_IS_NO_STATION);
02066
02067 return cost;
02068 }
02069
02076 static uint GetMinimalAirportDistanceToTile(TileIterator &it, TileIndex town_tile)
02077 {
02078 uint mindist = UINT_MAX;
02079
02080 for (TileIndex cur_tile = it; cur_tile != INVALID_TILE; cur_tile = ++it) {
02081 mindist = min(mindist, DistanceManhattan(town_tile, cur_tile));
02082 }
02083
02084 return mindist;
02085 }
02086
02096 uint8 GetAirportNoiseLevelForTown(const AirportSpec *as, TileIterator &it, TileIndex town_tile)
02097 {
02098
02099
02100 if (as->noise_level < 2) return as->noise_level;
02101
02102 uint distance = GetMinimalAirportDistanceToTile(it, town_tile);
02103
02104
02105
02106
02107
02108 uint8 town_tolerance_distance = 8 + (_settings_game.difficulty.town_council_tolerance * 4);
02109
02110
02111
02112 uint noise_reduction = distance / town_tolerance_distance;
02113
02114
02115
02116 return noise_reduction >= as->noise_level ? 1 : as->noise_level - noise_reduction;
02117 }
02118
02126 Town *AirportGetNearestTown(const AirportSpec *as, const TileIterator &it)
02127 {
02128 Town *t, *nearest = NULL;
02129 uint add = as->size_x + as->size_y - 2;
02130 uint mindist = UINT_MAX - add;
02131 FOR_ALL_TOWNS(t) {
02132 if (DistanceManhattan(t->xy, it) < mindist + add) {
02133 TileIterator *copy = it.Clone();
02134 uint dist = GetMinimalAirportDistanceToTile(*copy, t->xy);
02135 delete copy;
02136 if (dist < mindist) {
02137 nearest = t;
02138 mindist = dist;
02139 }
02140 }
02141 }
02142
02143 return nearest;
02144 }
02145
02146
02148 void UpdateAirportsNoise()
02149 {
02150 Town *t;
02151 const Station *st;
02152
02153 FOR_ALL_TOWNS(t) t->noise_reached = 0;
02154
02155 FOR_ALL_STATIONS(st) {
02156 if (st->airport.tile != INVALID_TILE && st->airport.type != AT_OILRIG) {
02157 const AirportSpec *as = st->airport.GetSpec();
02158 AirportTileIterator it(st);
02159 Town *nearest = AirportGetNearestTown(as, it);
02160 nearest->noise_reached += GetAirportNoiseLevelForTown(as, it, nearest->xy);
02161 }
02162 }
02163 }
02164
02178 CommandCost CmdBuildAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02179 {
02180 StationID station_to_join = GB(p2, 16, 16);
02181 bool reuse = (station_to_join != NEW_STATION);
02182 if (!reuse) station_to_join = INVALID_STATION;
02183 bool distant_join = (station_to_join != INVALID_STATION);
02184 byte airport_type = GB(p1, 0, 8);
02185 byte layout = GB(p1, 8, 8);
02186
02187 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
02188
02189 if (airport_type >= NUM_AIRPORTS) return CMD_ERROR;
02190
02191 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
02192 if (ret.Failed()) return ret;
02193
02194
02195 const AirportSpec *as = AirportSpec::Get(airport_type);
02196 if (!as->IsAvailable() || layout >= as->num_table) return CMD_ERROR;
02197
02198 Direction rotation = as->rotation[layout];
02199 int w = as->size_x;
02200 int h = as->size_y;
02201 if (rotation == DIR_E || rotation == DIR_W) Swap(w, h);
02202 TileArea airport_area = TileArea(tile, w, h);
02203
02204 if (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread) {
02205 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
02206 }
02207
02208 CommandCost cost = CheckFlatLand(airport_area, flags);
02209 if (cost.Failed()) return cost;
02210
02211
02212 AirportTileTableIterator iter(as->table[layout], tile);
02213 Town *nearest = AirportGetNearestTown(as, iter);
02214 uint newnoise_level = GetAirportNoiseLevelForTown(as, iter, nearest->xy);
02215
02216
02217 StringID authority_refuse_message = STR_NULL;
02218 Town *authority_refuse_town = NULL;
02219
02220 if (_settings_game.economy.station_noise_level) {
02221
02222 if ((nearest->noise_reached + newnoise_level) > nearest->MaxTownNoise()) {
02223 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE;
02224 authority_refuse_town = nearest;
02225 }
02226 } else {
02227 Town *t = ClosestTownFromTile(tile, UINT_MAX);
02228 uint num = 0;
02229 const Station *st;
02230 FOR_ALL_STATIONS(st) {
02231 if (st->town == t && (st->facilities & FACIL_AIRPORT) && st->airport.type != AT_OILRIG) num++;
02232 }
02233 if (num >= 2) {
02234 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT;
02235 authority_refuse_town = t;
02236 }
02237 }
02238
02239 if (authority_refuse_message != STR_NULL) {
02240 SetDParam(0, authority_refuse_town->index);
02241 return_cmd_error(authority_refuse_message);
02242 }
02243
02244 Station *st = NULL;
02245 ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p2, 0), airport_area, &st);
02246 if (ret.Failed()) return ret;
02247
02248
02249 if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
02250
02251 ret = BuildStationPart(&st, flags, reuse, airport_area, (GetAirport(airport_type)->flags & AirportFTAClass::AIRPLANES) ? STATIONNAMING_AIRPORT : STATIONNAMING_HELIPORT);
02252 if (ret.Failed()) return ret;
02253
02254 if (st != NULL && st->airport.tile != INVALID_TILE) {
02255 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT);
02256 }
02257
02258 for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
02259 cost.AddCost(_price[PR_BUILD_STATION_AIRPORT]);
02260 }
02261
02262 if (flags & DC_EXEC) {
02263
02264 nearest->noise_reached += newnoise_level;
02265
02266 st->AddFacility(FACIL_AIRPORT, tile);
02267 st->airport.type = airport_type;
02268 st->airport.layout = layout;
02269 st->airport.flags = 0;
02270 st->airport.rotation = rotation;
02271
02272 st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TRY);
02273
02274 for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
02275 MakeAirport(iter, st->owner, st->index, iter.GetStationGfx(), WATER_CLASS_INVALID);
02276 SetStationTileRandomBits(iter, GB(Random(), 0, 4));
02277 st->airport.Add(iter);
02278
02279 if (AirportTileSpec::Get(GetTranslatedAirportTileID(iter.GetStationGfx()))->animation.status != ANIM_STATUS_NO_ANIMATION) AddAnimatedTile(iter);
02280 }
02281
02282
02283 for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
02284 AirportTileAnimationTrigger(st, iter, AAT_BUILT);
02285 }
02286
02287 UpdateAirplanesOnNewStation(st);
02288
02289 Company::Get(st->owner)->infrastructure.airport++;
02290 DirtyCompanyInfrastructureWindows(st->owner);
02291
02292 st->UpdateVirtCoord();
02293 UpdateStationAcceptance(st, false);
02294 st->RecomputeIndustriesNear();
02295 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
02296 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
02297 InvalidateWindowData(WC_STATION_VIEW, st->index, -1);
02298
02299 if (_settings_game.economy.station_noise_level) {
02300 SetWindowDirty(WC_TOWN_VIEW, st->town->index);
02301 }
02302 }
02303
02304 return cost;
02305 }
02306
02313 static CommandCost RemoveAirport(TileIndex tile, DoCommandFlag flags)
02314 {
02315 Station *st = Station::GetByTile(tile);
02316
02317 if (_current_company != OWNER_WATER) {
02318 CommandCost ret = CheckOwnership(st->owner);
02319 if (ret.Failed()) return ret;
02320 }
02321
02322 tile = st->airport.tile;
02323
02324 CommandCost cost(EXPENSES_CONSTRUCTION);
02325
02326 const Aircraft *a;
02327 FOR_ALL_AIRCRAFT(a) {
02328 if (!a->IsNormalAircraft()) continue;
02329 if (a->targetairport == st->index && a->state != FLYING) return CMD_ERROR;
02330 }
02331
02332 if (flags & DC_EXEC) {
02333 const AirportSpec *as = st->airport.GetSpec();
02334
02335
02336
02337 AirportTileIterator it(st);
02338 Town *nearest = AirportGetNearestTown(as, it);
02339 nearest->noise_reached -= GetAirportNoiseLevelForTown(as, it, nearest->xy);
02340 }
02341
02342 TILE_AREA_LOOP(tile_cur, st->airport) {
02343 if (!st->TileBelongsToAirport(tile_cur)) continue;
02344
02345 CommandCost ret = EnsureNoVehicleOnGround(tile_cur);
02346 if (ret.Failed()) return ret;
02347
02348 cost.AddCost(_price[PR_CLEAR_STATION_AIRPORT]);
02349
02350 if (flags & DC_EXEC) {
02351 if (IsHangarTile(tile_cur)) OrderBackup::Reset(tile_cur, false);
02352 DeleteAnimatedTile(tile_cur);
02353 DoClearSquare(tile_cur);
02354 DeleteNewGRFInspectWindow(GSF_AIRPORTTILES, tile_cur);
02355 }
02356 }
02357
02358 if (flags & DC_EXEC) {
02359
02360 delete st->airport.psa;
02361
02362 for (uint i = 0; i < st->airport.GetNumHangars(); ++i) {
02363 DeleteWindowById(
02364 WC_VEHICLE_DEPOT, st->airport.GetHangarTile(i)
02365 );
02366 }
02367
02368 st->rect.AfterRemoveRect(st, st->airport);
02369
02370 st->airport.Clear();
02371 st->facilities &= ~FACIL_AIRPORT;
02372
02373 InvalidateWindowData(WC_STATION_VIEW, st->index, -1);
02374
02375 if (_settings_game.economy.station_noise_level) {
02376 SetWindowDirty(WC_TOWN_VIEW, st->town->index);
02377 }
02378
02379 Company::Get(st->owner)->infrastructure.airport--;
02380 DirtyCompanyInfrastructureWindows(st->owner);
02381
02382 st->UpdateVirtCoord();
02383 st->RecomputeIndustriesNear();
02384 DeleteStationIfEmpty(st);
02385 DeleteNewGRFInspectWindow(GSF_AIRPORTS, st->index);
02386 }
02387
02388 return cost;
02389 }
02390
02400 CommandCost CmdOpenCloseAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02401 {
02402 if (!Station::IsValidID(p1)) return CMD_ERROR;
02403 Station *st = Station::Get(p1);
02404
02405 if (!(st->facilities & FACIL_AIRPORT) || st->owner == OWNER_NONE) return CMD_ERROR;
02406
02407 CommandCost ret = CheckOwnership(st->owner);
02408 if (ret.Failed()) return ret;
02409
02410 if (flags & DC_EXEC) {
02411 st->airport.flags ^= AIRPORT_CLOSED_block;
02412 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_CLOSE_AIRPORT);
02413 }
02414 return CommandCost();
02415 }
02416
02423 bool HasStationInUse(StationID station, bool include_company, CompanyID company)
02424 {
02425 const Vehicle *v;
02426 FOR_ALL_VEHICLES(v) {
02427 if ((v->owner == company) == include_company) {
02428 const Order *order;
02429 FOR_VEHICLE_ORDERS(v, order) {
02430 if ((order->IsType(OT_GOTO_STATION) || order->IsType(OT_GOTO_WAYPOINT)) && order->GetDestination() == station) {
02431 return true;
02432 }
02433 }
02434 }
02435 }
02436 return false;
02437 }
02438
02439 static const TileIndexDiffC _dock_tileoffs_chkaround[] = {
02440 {-1, 0},
02441 { 0, 0},
02442 { 0, 0},
02443 { 0, -1}
02444 };
02445 static const byte _dock_w_chk[4] = { 2, 1, 2, 1 };
02446 static const byte _dock_h_chk[4] = { 1, 2, 1, 2 };
02447
02457 CommandCost CmdBuildDock(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02458 {
02459 StationID station_to_join = GB(p2, 16, 16);
02460 bool reuse = (station_to_join != NEW_STATION);
02461 if (!reuse) station_to_join = INVALID_STATION;
02462 bool distant_join = (station_to_join != INVALID_STATION);
02463
02464 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
02465
02466 DiagDirection direction = GetInclinedSlopeDirection(GetTileSlope(tile));
02467 if (direction == INVALID_DIAGDIR) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02468 direction = ReverseDiagDir(direction);
02469
02470
02471 if (HasTileWaterGround(tile)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02472
02473 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
02474 if (ret.Failed()) return ret;
02475
02476 if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
02477
02478 ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02479 if (ret.Failed()) return ret;
02480
02481 TileIndex tile_cur = tile + TileOffsByDiagDir(direction);
02482
02483 if (!IsTileType(tile_cur, MP_WATER) || !IsTileFlat(tile_cur)) {
02484 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02485 }
02486
02487 if (MayHaveBridgeAbove(tile_cur) && IsBridgeAbove(tile_cur)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
02488
02489
02490 WaterClass wc = GetWaterClass(tile_cur);
02491
02492 ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02493 if (ret.Failed()) return ret;
02494
02495 tile_cur += TileOffsByDiagDir(direction);
02496 if (!IsTileType(tile_cur, MP_WATER) || !IsTileFlat(tile_cur)) {
02497 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02498 }
02499
02500 TileArea dock_area = TileArea(tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
02501 _dock_w_chk[direction], _dock_h_chk[direction]);
02502
02503
02504 Station *st = NULL;
02505 ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p1, 0), dock_area, &st);
02506 if (ret.Failed()) return ret;
02507
02508
02509 if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
02510
02511 ret = BuildStationPart(&st, flags, reuse, dock_area, STATIONNAMING_DOCK);
02512 if (ret.Failed()) return ret;
02513
02514 if (st != NULL && st->dock_tile != INVALID_TILE) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_DOCK);
02515
02516 if (flags & DC_EXEC) {
02517 st->dock_tile = tile;
02518 st->AddFacility(FACIL_DOCK, tile);
02519
02520 st->rect.BeforeAddRect(dock_area.tile, dock_area.w, dock_area.h, StationRect::ADD_TRY);
02521
02522
02523
02524 if (wc == WATER_CLASS_CANAL) {
02525 Company::Get(st->owner)->infrastructure.water++;
02526 }
02527 Company::Get(st->owner)->infrastructure.station += 2;
02528 DirtyCompanyInfrastructureWindows(st->owner);
02529
02530 MakeDock(tile, st->owner, st->index, direction, wc);
02531
02532 st->UpdateVirtCoord();
02533 UpdateStationAcceptance(st, false);
02534 st->RecomputeIndustriesNear();
02535 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
02536 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
02537 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_SHIPS);
02538 }
02539
02540 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_STATION_DOCK]);
02541 }
02542
02549 static CommandCost RemoveDock(TileIndex tile, DoCommandFlag flags)
02550 {
02551 Station *st = Station::GetByTile(tile);
02552 CommandCost ret = CheckOwnership(st->owner);
02553 if (ret.Failed()) return ret;
02554
02555 TileIndex docking_location = TILE_ADD(st->dock_tile, ToTileIndexDiff(GetDockOffset(st->dock_tile)));
02556
02557 TileIndex tile1 = st->dock_tile;
02558 TileIndex tile2 = tile1 + TileOffsByDiagDir(GetDockDirection(tile1));
02559
02560 ret = EnsureNoVehicleOnGround(tile1);
02561 if (ret.Succeeded()) ret = EnsureNoVehicleOnGround(tile2);
02562 if (ret.Failed()) return ret;
02563
02564 if (flags & DC_EXEC) {
02565 DoClearSquare(tile1);
02566 MarkTileDirtyByTile(tile1);
02567 MakeWaterKeepingClass(tile2, st->owner);
02568
02569 st->rect.AfterRemoveTile(st, tile1);
02570 st->rect.AfterRemoveTile(st, tile2);
02571
02572 st->dock_tile = INVALID_TILE;
02573 st->facilities &= ~FACIL_DOCK;
02574
02575 Company::Get(st->owner)->infrastructure.station -= 2;
02576 DirtyCompanyInfrastructureWindows(st->owner);
02577
02578 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_SHIPS);
02579 st->UpdateVirtCoord();
02580 st->RecomputeIndustriesNear();
02581 DeleteStationIfEmpty(st);
02582
02583
02584
02585
02586
02587 Ship *s;
02588 FOR_ALL_SHIPS(s) {
02589 if (s->current_order.IsType(OT_LOADING) && s->tile == docking_location) {
02590 s->LeaveStation();
02591 }
02592
02593 if (s->dest_tile == docking_location) {
02594 s->dest_tile = 0;
02595 s->current_order.Free();
02596 }
02597 }
02598 }
02599
02600 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_STATION_DOCK]);
02601 }
02602
02603 #include "table/station_land.h"
02604
02605 const DrawTileSprites *GetStationTileLayout(StationType st, byte gfx)
02606 {
02607 return &_station_display_datas[st][gfx];
02608 }
02609
02619 bool SplitGroundSpriteForOverlay(const TileInfo *ti, SpriteID *ground, RailTrackOffset *overlay_offset)
02620 {
02621 bool snow_desert;
02622 switch (*ground) {
02623 case SPR_RAIL_TRACK_X:
02624 snow_desert = false;
02625 *overlay_offset = RTO_X;
02626 break;
02627
02628 case SPR_RAIL_TRACK_Y:
02629 snow_desert = false;
02630 *overlay_offset = RTO_Y;
02631 break;
02632
02633 case SPR_RAIL_TRACK_X_SNOW:
02634 snow_desert = true;
02635 *overlay_offset = RTO_X;
02636 break;
02637
02638 case SPR_RAIL_TRACK_Y_SNOW:
02639 snow_desert = true;
02640 *overlay_offset = RTO_Y;
02641 break;
02642
02643 default:
02644 return false;
02645 }
02646
02647 if (ti != NULL) {
02648
02649 switch (_settings_game.game_creation.landscape) {
02650 case LT_ARCTIC:
02651 snow_desert = (uint)ti->z > GetSnowLine() * TILE_HEIGHT;
02652 break;
02653
02654 case LT_TROPIC:
02655 snow_desert = GetTropicZone(ti->tile) == TROPICZONE_DESERT;
02656 break;
02657
02658 default:
02659 break;
02660 }
02661 }
02662
02663 *ground = snow_desert ? SPR_FLAT_SNOW_DESERT_TILE : SPR_FLAT_GRASS_TILE;
02664 return true;
02665 }
02666
02667 static void DrawTile_Station(TileInfo *ti)
02668 {
02669 const NewGRFSpriteLayout *layout = NULL;
02670 DrawTileSprites tmp_rail_layout;
02671 const DrawTileSprites *t = NULL;
02672 RoadTypes roadtypes;
02673 int32 total_offset;
02674 const RailtypeInfo *rti = NULL;
02675 uint32 relocation = 0;
02676 uint32 ground_relocation = 0;
02677 BaseStation *st = NULL;
02678 const StationSpec *statspec = NULL;
02679 uint tile_layout = 0;
02680
02681 if (HasStationRail(ti->tile)) {
02682 rti = GetRailTypeInfo(GetRailType(ti->tile));
02683 roadtypes = ROADTYPES_NONE;
02684 total_offset = rti->GetRailtypeSpriteOffset();
02685
02686 if (IsCustomStationSpecIndex(ti->tile)) {
02687
02688 st = BaseStation::GetByTile(ti->tile);
02689 statspec = st->speclist[GetCustomStationSpecIndex(ti->tile)].spec;
02690
02691 if (statspec != NULL) {
02692 tile_layout = GetStationGfx(ti->tile);
02693
02694 if (HasBit(statspec->callback_mask, CBM_STATION_SPRITE_LAYOUT)) {
02695 uint16 callback = GetStationCallback(CBID_STATION_SPRITE_LAYOUT, 0, 0, statspec, st, ti->tile);
02696 if (callback != CALLBACK_FAILED) tile_layout = (callback & ~1) + GetRailStationAxis(ti->tile);
02697 }
02698
02699
02700 if (statspec->renderdata != NULL) {
02701 layout = &statspec->renderdata[tile_layout < statspec->tiles ? tile_layout : (uint)GetRailStationAxis(ti->tile)];
02702 if (!layout->NeedsPreprocessing()) {
02703 t = layout;
02704 layout = NULL;
02705 }
02706 }
02707 }
02708 }
02709 } else {
02710 roadtypes = IsRoadStop(ti->tile) ? GetRoadTypes(ti->tile) : ROADTYPES_NONE;
02711 total_offset = 0;
02712 }
02713
02714 StationGfx gfx = GetStationGfx(ti->tile);
02715 if (IsAirport(ti->tile)) {
02716 gfx = GetAirportGfx(ti->tile);
02717 if (gfx >= NEW_AIRPORTTILE_OFFSET) {
02718 const AirportTileSpec *ats = AirportTileSpec::Get(gfx);
02719 if (ats->grf_prop.spritegroup[0] != NULL && DrawNewAirportTile(ti, Station::GetByTile(ti->tile), gfx, ats)) {
02720 return;
02721 }
02722
02723
02724 assert(ats->grf_prop.subst_id != INVALID_AIRPORTTILE);
02725 gfx = ats->grf_prop.subst_id;
02726 }
02727 switch (gfx) {
02728 case APT_RADAR_GRASS_FENCE_SW:
02729 t = &_station_display_datas_airport_radar_grass_fence_sw[GetAnimationFrame(ti->tile)];
02730 break;
02731 case APT_GRASS_FENCE_NE_FLAG:
02732 t = &_station_display_datas_airport_flag_grass_fence_ne[GetAnimationFrame(ti->tile)];
02733 break;
02734 case APT_RADAR_FENCE_SW:
02735 t = &_station_display_datas_airport_radar_fence_sw[GetAnimationFrame(ti->tile)];
02736 break;
02737 case APT_RADAR_FENCE_NE:
02738 t = &_station_display_datas_airport_radar_fence_ne[GetAnimationFrame(ti->tile)];
02739 break;
02740 case APT_GRASS_FENCE_NE_FLAG_2:
02741 t = &_station_display_datas_airport_flag_grass_fence_ne_2[GetAnimationFrame(ti->tile)];
02742 break;
02743 }
02744 }
02745
02746 Owner owner = GetTileOwner(ti->tile);
02747
02748 PaletteID palette;
02749 if (Company::IsValidID(owner)) {
02750 palette = COMPANY_SPRITE_COLOUR(owner);
02751 } else {
02752
02753 palette = PALETTE_TO_GREY;
02754 }
02755
02756 if (layout == NULL && (t == NULL || t->seq == NULL)) t = GetStationTileLayout(GetStationType(ti->tile), gfx);
02757
02758
02759 if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile)) {
02760 if (statspec != NULL && HasBit(statspec->flags, SSF_CUSTOM_FOUNDATIONS)) {
02761
02762
02763 uint edge_info = 0;
02764 int z;
02765 Slope slope = GetFoundationPixelSlope(ti->tile, &z);
02766 if (!HasFoundationNW(ti->tile, slope, z)) SetBit(edge_info, 0);
02767 if (!HasFoundationNE(ti->tile, slope, z)) SetBit(edge_info, 1);
02768 SpriteID image = GetCustomStationFoundationRelocation(statspec, st, ti->tile, tile_layout, edge_info);
02769 if (image == 0) goto draw_default_foundation;
02770
02771 if (HasBit(statspec->flags, SSF_EXTENDED_FOUNDATIONS)) {
02772
02773
02774 static const uint8 foundation_parts[] = {
02775 0, 0, 0, 0,
02776 0, 1, 2, 3,
02777 0, 4, 5, 6,
02778 7, 8, 9
02779 };
02780
02781 AddSortableSpriteToDraw(image + foundation_parts[ti->tileh], PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
02782 } else {
02783
02784
02785
02786
02787 static const uint8 composite_foundation_parts[] = {
02788
02789 0x00, 0xD1, 0xE4, 0xE0,
02790
02791 0xCA, 0xC9, 0xC4, 0xC0,
02792
02793 0xD2, 0x91, 0xE4, 0xA0,
02794
02795 0x4A, 0x09, 0x44
02796 };
02797
02798 uint8 parts = composite_foundation_parts[ti->tileh];
02799
02800
02801
02802 if (HasBit(edge_info, 0)) ClrBit(parts, 6);
02803 if (HasBit(edge_info, 1)) ClrBit(parts, 7);
02804
02805 if (parts == 0) {
02806
02807
02808
02809 goto draw_default_foundation;
02810 }
02811
02812 StartSpriteCombine();
02813 for (int i = 0; i < 8; i++) {
02814 if (HasBit(parts, i)) {
02815 AddSortableSpriteToDraw(image + i, PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
02816 }
02817 }
02818 EndSpriteCombine();
02819 }
02820
02821 OffsetGroundSprite(31, 1);
02822 ti->z += ApplyPixelFoundationToSlope(FOUNDATION_LEVELED, &ti->tileh);
02823 } else {
02824 draw_default_foundation:
02825 DrawFoundation(ti, FOUNDATION_LEVELED);
02826 }
02827 }
02828
02829 if (IsBuoy(ti->tile)) {
02830 DrawWaterClassGround(ti);
02831 SpriteID sprite = GetCanalSprite(CF_BUOY, ti->tile);
02832 if (sprite != 0) total_offset = sprite - SPR_IMG_BUOY;
02833 } else if (IsDock(ti->tile) || (IsOilRig(ti->tile) && IsTileOnWater(ti->tile))) {
02834 if (ti->tileh == SLOPE_FLAT) {
02835 DrawWaterClassGround(ti);
02836 } else {
02837 assert(IsDock(ti->tile));
02838 TileIndex water_tile = ti->tile + TileOffsByDiagDir(GetDockDirection(ti->tile));
02839 WaterClass wc = GetWaterClass(water_tile);
02840 if (wc == WATER_CLASS_SEA) {
02841 DrawShoreTile(ti->tileh);
02842 } else {
02843 DrawClearLandTile(ti, 3);
02844 }
02845 }
02846 } else {
02847 if (layout != NULL) {
02848
02849 bool separate_ground = HasBit(statspec->flags, SSF_SEPARATE_GROUND);
02850 uint32 var10_values = layout->PrepareLayout(total_offset, rti->fallback_railtype, 0, 0, separate_ground);
02851 uint8 var10;
02852 FOR_EACH_SET_BIT(var10, var10_values) {
02853 uint32 var10_relocation = GetCustomStationRelocation(statspec, st, ti->tile, var10);
02854 layout->ProcessRegisters(var10, var10_relocation, separate_ground);
02855 }
02856 tmp_rail_layout.seq = layout->GetLayout(&tmp_rail_layout.ground);
02857 t = &tmp_rail_layout;
02858 total_offset = 0;
02859 } else if (statspec != NULL) {
02860
02861 ground_relocation = relocation = GetCustomStationRelocation(statspec, st, ti->tile, 0);
02862 if (HasBit(statspec->flags, SSF_SEPARATE_GROUND)) {
02863 ground_relocation = GetCustomStationRelocation(statspec, st, ti->tile, 1);
02864 }
02865 ground_relocation += rti->fallback_railtype;
02866 }
02867
02868 SpriteID image = t->ground.sprite;
02869 PaletteID pal = t->ground.pal;
02870 RailTrackOffset overlay_offset;
02871 if (rti != NULL && rti->UsesOverlay() && SplitGroundSpriteForOverlay(ti, &image, &overlay_offset)) {
02872 SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
02873 DrawGroundSprite(image, PAL_NONE);
02874 DrawGroundSprite(ground + overlay_offset, PAL_NONE);
02875
02876 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationReservation(ti->tile)) {
02877 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
02878 DrawGroundSprite(overlay + overlay_offset, PALETTE_CRASH);
02879 }
02880 } else {
02881 image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
02882 if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
02883 DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
02884
02885
02886 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationRail(ti->tile) && HasStationReservation(ti->tile)) {
02887 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
02888 DrawGroundSprite(GetRailStationAxis(ti->tile) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH);
02889 }
02890 }
02891 }
02892
02893 if (HasStationRail(ti->tile) && HasCatenaryDrawn(GetRailType(ti->tile))) DrawCatenary(ti);
02894
02895 if (HasBit(roadtypes, ROADTYPE_TRAM)) {
02896 Axis axis = GetRoadStopDir(ti->tile) == DIAGDIR_NE ? AXIS_X : AXIS_Y;
02897 DrawGroundSprite((HasBit(roadtypes, ROADTYPE_ROAD) ? SPR_TRAMWAY_OVERLAY : SPR_TRAMWAY_TRAM) + (axis ^ 1), PAL_NONE);
02898 DrawTramCatenary(ti, axis == AXIS_X ? ROAD_X : ROAD_Y);
02899 }
02900
02901 if (IsRailWaypoint(ti->tile)) {
02902
02903 total_offset = 0;
02904 }
02905
02906 DrawRailTileSeq(ti, t, TO_BUILDINGS, total_offset, relocation, palette);
02907 }
02908
02909 void StationPickerDrawSprite(int x, int y, StationType st, RailType railtype, RoadType roadtype, int image)
02910 {
02911 int32 total_offset = 0;
02912 PaletteID pal = COMPANY_SPRITE_COLOUR(_local_company);
02913 const DrawTileSprites *t = GetStationTileLayout(st, image);
02914 const RailtypeInfo *rti = NULL;
02915
02916 if (railtype != INVALID_RAILTYPE) {
02917 rti = GetRailTypeInfo(railtype);
02918 total_offset = rti->GetRailtypeSpriteOffset();
02919 }
02920
02921 SpriteID img = t->ground.sprite;
02922 RailTrackOffset overlay_offset;
02923 if (rti != NULL && rti->UsesOverlay() && SplitGroundSpriteForOverlay(NULL, &img, &overlay_offset)) {
02924 SpriteID ground = GetCustomRailSprite(rti, INVALID_TILE, RTSG_GROUND);
02925 DrawSprite(img, PAL_NONE, x, y);
02926 DrawSprite(ground + overlay_offset, PAL_NONE, x, y);
02927 } else {
02928 DrawSprite(img + total_offset, HasBit(img, PALETTE_MODIFIER_COLOUR) ? pal : PAL_NONE, x, y);
02929 }
02930
02931 if (roadtype == ROADTYPE_TRAM) {
02932 DrawSprite(SPR_TRAMWAY_TRAM + (t->ground.sprite == SPR_ROAD_PAVED_STRAIGHT_X ? 1 : 0), PAL_NONE, x, y);
02933 }
02934
02935
02936 DrawRailTileSeqInGUI(x, y, t, st == STATION_WAYPOINT ? 0 : total_offset, 0, pal);
02937 }
02938
02939 static int GetSlopePixelZ_Station(TileIndex tile, uint x, uint y)
02940 {
02941 return GetTileMaxPixelZ(tile);
02942 }
02943
02944 static Foundation GetFoundation_Station(TileIndex tile, Slope tileh)
02945 {
02946 return FlatteningFoundation(tileh);
02947 }
02948
02949 static void GetTileDesc_Station(TileIndex tile, TileDesc *td)
02950 {
02951 td->owner[0] = GetTileOwner(tile);
02952 if (IsDriveThroughStopTile(tile)) {
02953 Owner road_owner = INVALID_OWNER;
02954 Owner tram_owner = INVALID_OWNER;
02955 RoadTypes rts = GetRoadTypes(tile);
02956 if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
02957 if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
02958
02959
02960 if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
02961 (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
02962 uint i = 1;
02963 if (road_owner != INVALID_OWNER) {
02964 td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
02965 td->owner[i] = road_owner;
02966 i++;
02967 }
02968 if (tram_owner != INVALID_OWNER) {
02969 td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
02970 td->owner[i] = tram_owner;
02971 }
02972 }
02973 }
02974 td->build_date = BaseStation::GetByTile(tile)->build_date;
02975
02976 if (HasStationTileRail(tile)) {
02977 const StationSpec *spec = GetStationSpec(tile);
02978
02979 if (spec != NULL) {
02980 td->station_class = StationClass::Get(spec->cls_id)->name;
02981 td->station_name = spec->name;
02982
02983 if (spec->grf_prop.grffile != NULL) {
02984 const GRFConfig *gc = GetGRFConfig(spec->grf_prop.grffile->grfid);
02985 td->grf = gc->GetName();
02986 }
02987 }
02988
02989 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
02990 td->rail_speed = rti->max_speed;
02991 }
02992
02993 if (IsAirport(tile)) {
02994 const AirportSpec *as = Station::GetByTile(tile)->airport.GetSpec();
02995 td->airport_class = AirportClass::Get(as->cls_id)->name;
02996 td->airport_name = as->name;
02997
02998 const AirportTileSpec *ats = AirportTileSpec::GetByTile(tile);
02999 td->airport_tile_name = ats->name;
03000
03001 if (as->grf_prop.grffile != NULL) {
03002 const GRFConfig *gc = GetGRFConfig(as->grf_prop.grffile->grfid);
03003 td->grf = gc->GetName();
03004 } else if (ats->grf_prop.grffile != NULL) {
03005 const GRFConfig *gc = GetGRFConfig(ats->grf_prop.grffile->grfid);
03006 td->grf = gc->GetName();
03007 }
03008 }
03009
03010 StringID str;
03011 switch (GetStationType(tile)) {
03012 default: NOT_REACHED();
03013 case STATION_RAIL: str = STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION; break;
03014 case STATION_AIRPORT:
03015 str = (IsHangar(tile) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR : STR_LAI_STATION_DESCRIPTION_AIRPORT);
03016 break;
03017 case STATION_TRUCK: str = STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA; break;
03018 case STATION_BUS: str = STR_LAI_STATION_DESCRIPTION_BUS_STATION; break;
03019 case STATION_OILRIG: str = STR_INDUSTRY_NAME_OIL_RIG; break;
03020 case STATION_DOCK: str = STR_LAI_STATION_DESCRIPTION_SHIP_DOCK; break;
03021 case STATION_BUOY: str = STR_LAI_STATION_DESCRIPTION_BUOY; break;
03022 case STATION_WAYPOINT: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
03023 }
03024 td->str = str;
03025 }
03026
03027
03028 static TrackStatus GetTileTrackStatus_Station(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
03029 {
03030 TrackBits trackbits = TRACK_BIT_NONE;
03031
03032 switch (mode) {
03033 case TRANSPORT_RAIL:
03034 if (HasStationRail(tile) && !IsStationTileBlocked(tile)) {
03035 trackbits = TrackToTrackBits(GetRailStationTrack(tile));
03036 }
03037 break;
03038
03039 case TRANSPORT_WATER:
03040
03041 if (IsBuoy(tile)) {
03042 trackbits = TRACK_BIT_ALL;
03043
03044 if (TileX(tile) == 0) trackbits &= ~(TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT);
03045
03046 if (TileY(tile) == 0) trackbits &= ~(TRACK_BIT_Y | TRACK_BIT_LEFT | TRACK_BIT_UPPER);
03047 }
03048 break;
03049
03050 case TRANSPORT_ROAD:
03051 if ((GetRoadTypes(tile) & sub_mode) != 0 && IsRoadStop(tile)) {
03052 DiagDirection dir = GetRoadStopDir(tile);
03053 Axis axis = DiagDirToAxis(dir);
03054
03055 if (side != INVALID_DIAGDIR) {
03056 if (axis != DiagDirToAxis(side) || (IsStandardRoadStopTile(tile) && dir != side)) break;
03057 }
03058
03059 trackbits = AxisToTrackBits(axis);
03060 }
03061 break;
03062
03063 default:
03064 break;
03065 }
03066
03067 return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits), TRACKDIR_BIT_NONE);
03068 }
03069
03070
03071 static void TileLoop_Station(TileIndex tile)
03072 {
03073
03074
03075 switch (GetStationType(tile)) {
03076 case STATION_AIRPORT:
03077 AirportTileAnimationTrigger(Station::GetByTile(tile), tile, AAT_TILELOOP);
03078 break;
03079
03080 case STATION_DOCK:
03081 if (!IsTileFlat(tile)) break;
03082
03083 case STATION_OILRIG:
03084 case STATION_BUOY:
03085 TileLoop_Water(tile);
03086 break;
03087
03088 default: break;
03089 }
03090 }
03091
03092
03093 static void AnimateTile_Station(TileIndex tile)
03094 {
03095 if (HasStationRail(tile)) {
03096 AnimateStationTile(tile);
03097 return;
03098 }
03099
03100 if (IsAirport(tile)) {
03101 AnimateAirportTile(tile);
03102 }
03103 }
03104
03105
03106 static bool ClickTile_Station(TileIndex tile)
03107 {
03108 const BaseStation *bst = BaseStation::GetByTile(tile);
03109
03110 if (bst->facilities & FACIL_WAYPOINT) {
03111 ShowWaypointWindow(Waypoint::From(bst));
03112 } else if (IsHangar(tile)) {
03113 const Station *st = Station::From(bst);
03114 ShowDepotWindow(st->airport.GetHangarTile(st->airport.GetHangarNum(tile)), VEH_AIRCRAFT);
03115 } else {
03116 ShowStationViewWindow(bst->index);
03117 }
03118 return true;
03119 }
03120
03121 static VehicleEnterTileStatus VehicleEnter_Station(Vehicle *v, TileIndex tile, int x, int y)
03122 {
03123 if (v->type == VEH_TRAIN) {
03124 StationID station_id = GetStationIndex(tile);
03125 if (!v->current_order.ShouldStopAtStation(v, station_id)) return VETSB_CONTINUE;
03126 if (!IsRailStation(tile) || !v->IsFrontEngine()) return VETSB_CONTINUE;
03127
03128 int station_ahead;
03129 int station_length;
03130 int stop = GetTrainStopLocation(station_id, tile, Train::From(v), &station_ahead, &station_length);
03131
03132
03133
03134
03135
03136 if (stop + station_ahead - (int)TILE_SIZE >= station_length) return VETSB_CONTINUE;
03137
03138 DiagDirection dir = DirToDiagDir(v->direction);
03139
03140 x &= 0xF;
03141 y &= 0xF;
03142
03143 if (DiagDirToAxis(dir) != AXIS_X) Swap(x, y);
03144 if (y == TILE_SIZE / 2) {
03145 if (dir != DIAGDIR_SE && dir != DIAGDIR_SW) x = TILE_SIZE - 1 - x;
03146 stop &= TILE_SIZE - 1;
03147
03148 if (x == stop) {
03149 return VETSB_ENTERED_STATION | (VehicleEnterTileStatus)(station_id << VETS_STATION_ID_OFFSET);
03150 } else if (x < stop) {
03151 v->vehstatus |= VS_TRAIN_SLOWING;
03152 uint16 spd = max(0, (stop - x) * 20 - 15);
03153 if (spd < v->cur_speed) v->cur_speed = spd;
03154 }
03155 }
03156 } else if (v->type == VEH_ROAD) {
03157 RoadVehicle *rv = RoadVehicle::From(v);
03158 if (rv->state < RVSB_IN_ROAD_STOP && !IsReversingRoadTrackdir((Trackdir)rv->state) && rv->frame == 0) {
03159 if (IsRoadStop(tile) && rv->IsFrontEngine()) {
03160
03161 return RoadStop::GetByTile(tile, GetRoadStopType(tile))->Enter(rv) ? VETSB_CONTINUE : VETSB_CANNOT_ENTER;
03162 }
03163 }
03164 }
03165
03166 return VETSB_CONTINUE;
03167 }
03168
03173 void TriggerWatchedCargoCallbacks(Station *st)
03174 {
03175
03176 uint cargoes = 0;
03177 for (CargoID cid = 0; cid < NUM_CARGO; cid++) {
03178 if (HasBit(st->goods[cid].acceptance_pickup, GoodsEntry::GES_ACCEPTED_BIGTICK)) SetBit(cargoes, cid);
03179 }
03180
03181
03182 if (cargoes == 0) return;
03183
03184
03185 Rect r = st->GetCatchmentRect();
03186 TileArea ta(TileXY(r.left, r.top), TileXY(r.right, r.bottom));
03187 TILE_AREA_LOOP(tile, ta) {
03188 if (IsTileType(tile, MP_HOUSE)) {
03189 WatchedCargoCallback(tile, cargoes);
03190 }
03191 }
03192 }
03193
03200 static bool StationHandleBigTick(BaseStation *st)
03201 {
03202 if (!st->IsInUse()) {
03203 if (++st->delete_ctr >= 8) delete st;
03204 return false;
03205 }
03206
03207 if (Station::IsExpected(st)) {
03208 TriggerWatchedCargoCallbacks(Station::From(st));
03209
03210 for (CargoID i = 0; i < NUM_CARGO; i++) {
03211 ClrBit(Station::From(st)->goods[i].acceptance_pickup, GoodsEntry::GES_ACCEPTED_BIGTICK);
03212 }
03213 }
03214
03215
03216 if ((st->facilities & FACIL_WAYPOINT) == 0) UpdateStationAcceptance(Station::From(st), true);
03217
03218 return true;
03219 }
03220
03221 static inline void byte_inc_sat(byte *p)
03222 {
03223 byte b = *p + 1;
03224 if (b != 0) *p = b;
03225 }
03226
03227 static void UpdateStationRating(Station *st)
03228 {
03229 bool waiting_changed = false;
03230
03231 byte_inc_sat(&st->time_since_load);
03232 byte_inc_sat(&st->time_since_unload);
03233
03234 const CargoSpec *cs;
03235 FOR_ALL_CARGOSPECS(cs) {
03236 GoodsEntry *ge = &st->goods[cs->Index()];
03237
03238
03239
03240 if (!ge->HasRating() && ge->rating < INITIAL_STATION_RATING) {
03241 ge->rating++;
03242 }
03243
03244
03245 if (ge->HasRating()) {
03246 byte_inc_sat(&ge->time_since_pickup);
03247
03248 bool skip = false;
03249 int rating = 0;
03250 uint waiting = ge->cargo.TotalCount();
03251
03252
03253
03254
03255 uint num_dests = (uint)ge->cargo.Packets()->MapSize();
03256
03257
03258
03259
03260
03261
03262
03263 uint waiting_avg = waiting / (num_dests + 1);
03264
03265 if (HasBit(cs->callback_mask, CBM_CARGO_STATION_RATING_CALC)) {
03266
03267
03268
03269
03270 uint last_speed = ge->HasVehicleEverTriedLoading() ? ge->last_speed : 0xFF;
03271
03272 uint32 var18 = min(ge->time_since_pickup, 0xFF) | (min(ge->max_waiting_cargo, 0xFFFF) << 8) | (min(last_speed, 0xFF) << 24);
03273
03274 uint32 var10 = (st->last_vehicle_type == VEH_INVALID) ? 0x0 : (st->last_vehicle_type + 0x10);
03275 uint16 callback = GetCargoCallback(CBID_CARGO_STATION_RATING_CALC, var10, var18, cs);
03276 if (callback != CALLBACK_FAILED) {
03277 skip = true;
03278 rating = GB(callback, 0, 14);
03279
03280
03281 if (HasBit(callback, 14)) rating -= 0x4000;
03282 }
03283 }
03284
03285 if (!skip) {
03286 int b = ge->last_speed - 85;
03287 if (b >= 0) rating += b >> 2;
03288
03289 byte waittime = ge->time_since_pickup;
03290 if (st->last_vehicle_type == VEH_SHIP) waittime >>= 2;
03291 (waittime > 21) ||
03292 (rating += 25, waittime > 12) ||
03293 (rating += 25, waittime > 6) ||
03294 (rating += 45, waittime > 3) ||
03295 (rating += 35, true);
03296
03297 (rating -= 90, ge->max_waiting_cargo > 1500) ||
03298 (rating += 55, ge->max_waiting_cargo > 1000) ||
03299 (rating += 35, ge->max_waiting_cargo > 600) ||
03300 (rating += 10, ge->max_waiting_cargo > 300) ||
03301 (rating += 20, ge->max_waiting_cargo > 100) ||
03302 (rating += 10, true);
03303 }
03304
03305 if (Company::IsValidID(st->owner) && HasBit(st->town->statues, st->owner)) rating += 26;
03306
03307 byte age = ge->last_age;
03308 (age >= 3) ||
03309 (rating += 10, age >= 2) ||
03310 (rating += 10, age >= 1) ||
03311 (rating += 13, true);
03312
03313 {
03314 int or_ = ge->rating;
03315
03316
03317 ge->rating = rating = or_ + Clamp(Clamp(rating, 0, 255) - or_, -2, 2);
03318
03319
03320
03321 if (rating <= 64 && waiting_avg >= 100) {
03322 int dec = Random() & 0x1F;
03323 if (waiting_avg < 200) dec &= 7;
03324 waiting -= (dec + 1) * num_dests;
03325 waiting_changed = true;
03326 }
03327
03328
03329 if (rating <= 127 && waiting != 0) {
03330 uint32 r = Random();
03331 if (rating <= (int)GB(r, 0, 7)) {
03332
03333 waiting = max((int)waiting - (int)((GB(r, 8, 2) - 1) * num_dests), 0);
03334 waiting_changed = true;
03335 }
03336 }
03337
03338
03339
03340
03341 static const uint WAITING_CARGO_THRESHOLD = 1 << 12;
03342 static const uint WAITING_CARGO_CUT_FACTOR = 1 << 6;
03343 static const uint MAX_WAITING_CARGO = 1 << 15;
03344
03345 if (waiting > WAITING_CARGO_THRESHOLD) {
03346 uint difference = waiting - WAITING_CARGO_THRESHOLD;
03347 waiting -= (difference / WAITING_CARGO_CUT_FACTOR);
03348
03349 waiting = min(waiting, MAX_WAITING_CARGO);
03350 waiting_changed = true;
03351 }
03352
03353
03354
03355 if (waiting_changed && waiting < ge->cargo.AvailableCount()) {
03356
03357
03358 ge->max_waiting_cargo = 0;
03359
03360
03361
03362
03363 StationCargoAmountMap waiting_per_source;
03364 ge->cargo.Truncate(ge->cargo.AvailableCount() - waiting, &waiting_per_source);
03365 for (StationCargoAmountMap::iterator i(waiting_per_source.begin()); i != waiting_per_source.end(); ++i) {
03366 Station *source_station = Station::GetIfValid(i->first);
03367 if (source_station == NULL) continue;
03368
03369 GoodsEntry &source_ge = source_station->goods[cs->Index()];
03370 source_ge.max_waiting_cargo = max(source_ge.max_waiting_cargo, i->second);
03371 }
03372 } else {
03373
03374 ge->max_waiting_cargo = waiting_avg;
03375 }
03376 }
03377 }
03378 }
03379
03380 StationID index = st->index;
03381 if (waiting_changed) {
03382 SetWindowDirty(WC_STATION_VIEW, index);
03383 } else {
03384 SetWindowWidgetDirty(WC_STATION_VIEW, index, WID_SV_ACCEPT_RATING_LIST);
03385 }
03386 }
03387
03396 void RerouteCargo(Station *st, CargoID c, StationID avoid, StationID avoid2)
03397 {
03398 GoodsEntry &ge = st->goods[c];
03399
03400
03401 ge.cargo.Reroute(UINT_MAX, &ge.cargo, avoid, avoid2, &ge);
03402
03403
03404 for (std::list<Vehicle *>::iterator it(st->loading_vehicles.begin()); it != st->loading_vehicles.end(); ++it) {
03405 for (Vehicle *v = *it; v != NULL; v = v->Next()) {
03406 if (v->cargo_type != c) continue;
03407 v->cargo.Reroute(UINT_MAX, &v->cargo, avoid, avoid2, &ge);
03408 }
03409 }
03410 }
03411
03420 void DeleteStaleLinks(Station *from)
03421 {
03422 for (CargoID c = 0; c < NUM_CARGO; ++c) {
03423 GoodsEntry &ge = from->goods[c];
03424 LinkGraph *lg = LinkGraph::GetIfValid(ge.link_graph);
03425 if (lg == NULL) continue;
03426 Node node = (*lg)[ge.node];
03427 for (EdgeIterator it(node.Begin()); it != node.End();) {
03428 Edge edge = it->second;
03429 Station *to = Station::Get((*lg)[it->first].Station());
03430 assert(to->goods[c].node == it->first);
03431 ++it;
03432 assert(_date >= edge.LastUpdate());
03433 uint timeout = LinkGraph::MIN_TIMEOUT_DISTANCE + (DistanceManhattan(from->xy, to->xy) >> 3);
03434 if ((uint)(_date - edge.LastUpdate()) > timeout) {
03435
03436
03437 bool updated = false;
03438 OrderList *l;
03439 FOR_ALL_ORDER_LISTS(l) {
03440 bool found_from = false;
03441 bool found_to = false;
03442 for (Order *order = l->GetFirstOrder(); order != NULL; order = order->next) {
03443 if (!order->IsType(OT_GOTO_STATION) && !order->IsType(OT_IMPLICIT)) continue;
03444 if (order->GetDestination() == from->index) {
03445 found_from = true;
03446 if (found_to) break;
03447 } else if (order->GetDestination() == to->index) {
03448 found_to = true;
03449 if (found_from) break;
03450 }
03451 }
03452 if (!found_to || !found_from) continue;
03453 for (Vehicle *v = l->GetFirstSharedVehicle(); !updated && v != NULL; v = v->NextShared()) {
03454
03455
03456
03457
03458
03459
03460 LinkRefresher::Run(v, false);
03461 if (edge.LastUpdate() == _date) updated = true;
03462 }
03463 if (updated) break;
03464 }
03465 if (!updated) {
03466
03467 node.RemoveEdge(to->goods[c].node);
03468 ge.flows.DeleteFlows(to->index);
03469 RerouteCargo(from, c, to->index, from->index);
03470 }
03471 } else if (edge.LastUnrestrictedUpdate() != INVALID_DATE && (uint)(_date - edge.LastUnrestrictedUpdate()) > timeout) {
03472 edge.Restrict();
03473 ge.flows.RestrictFlows(to->index);
03474 RerouteCargo(from, c, to->index, from->index);
03475 } else if (edge.LastRestrictedUpdate() != INVALID_DATE && (uint)(_date - edge.LastRestrictedUpdate()) > timeout) {
03476 edge.Release();
03477 }
03478 }
03479 assert(_date >= lg->LastCompression());
03480 if ((uint)(_date - lg->LastCompression()) > LinkGraph::COMPRESSION_INTERVAL) {
03481 lg->Compress();
03482 }
03483 }
03484 }
03485
03494 void IncreaseStats(Station *st, CargoID cargo, StationID next_station_id, uint capacity, uint usage)
03495 {
03496 GoodsEntry &ge1 = st->goods[cargo];
03497 Station *st2 = Station::Get(next_station_id);
03498 GoodsEntry &ge2 = st2->goods[cargo];
03499 LinkGraph *lg = NULL;
03500 if (ge1.link_graph == INVALID_LINK_GRAPH) {
03501 if (ge2.link_graph == INVALID_LINK_GRAPH) {
03502 if (LinkGraph::CanAllocateItem()) {
03503 lg = new LinkGraph(cargo);
03504 LinkGraphSchedule::Instance()->Queue(lg);
03505 ge2.link_graph = lg->index;
03506 ge2.node = lg->AddNode(st2);
03507 } else {
03508 DEBUG(misc, 0, "Can't allocate link graph");
03509 }
03510 } else {
03511 lg = LinkGraph::Get(ge2.link_graph);
03512 }
03513 if (lg) {
03514 ge1.link_graph = lg->index;
03515 ge1.node = lg->AddNode(st);
03516 }
03517 } else if (ge2.link_graph == INVALID_LINK_GRAPH) {
03518 lg = LinkGraph::Get(ge1.link_graph);
03519 ge2.link_graph = lg->index;
03520 ge2.node = lg->AddNode(st2);
03521 } else {
03522 lg = LinkGraph::Get(ge1.link_graph);
03523 if (ge1.link_graph != ge2.link_graph) {
03524 LinkGraph *lg2 = LinkGraph::Get(ge2.link_graph);
03525 if (lg->Size() < lg2->Size()) {
03526 LinkGraphSchedule::Instance()->Unqueue(lg);
03527 lg2->Merge(lg);
03528 lg = lg2;
03529 } else {
03530 LinkGraphSchedule::Instance()->Unqueue(lg2);
03531 lg->Merge(lg2);
03532 }
03533 }
03534 }
03535 if (lg != NULL) {
03536 (*lg)[ge1.node].UpdateEdge(ge2.node, capacity, usage);
03537 }
03538 }
03539
03546 void IncreaseStats(Station *st, const Vehicle *front, StationID next_station_id)
03547 {
03548 for (const Vehicle *v = front; v != NULL; v = v->Next()) {
03549 if (v->refit_cap > 0) {
03550
03551
03552
03553
03554
03555
03556 IncreaseStats(st, v->cargo_type, next_station_id, v->refit_cap,
03557 min(v->refit_cap, v->cargo.StoredCount()));
03558 }
03559 }
03560 }
03561
03562
03563 static void StationHandleSmallTick(BaseStation *st)
03564 {
03565 if ((st->facilities & FACIL_WAYPOINT) != 0 || !st->IsInUse()) return;
03566
03567 byte b = st->delete_ctr + 1;
03568 if (b >= STATION_RATING_TICKS) b = 0;
03569 st->delete_ctr = b;
03570
03571 if (b == 0) UpdateStationRating(Station::From(st));
03572 }
03573
03574 void OnTick_Station()
03575 {
03576 if (_game_mode == GM_EDITOR) return;
03577
03578 BaseStation *st;
03579 FOR_ALL_BASE_STATIONS(st) {
03580 StationHandleSmallTick(st);
03581
03582
03583 if (Station::IsExpected(st) && (_tick_counter + st->index) % STATION_LINKGRAPH_TICKS == 0) {
03584 DeleteStaleLinks(Station::From(st));
03585 };
03586
03587
03588
03589
03590 if ((_tick_counter + st->index) % STATION_ACCEPTANCE_TICKS == 0) {
03591
03592 if (!StationHandleBigTick(st)) continue;
03593 TriggerStationAnimation(st, st->xy, SAT_250_TICKS);
03594 if (Station::IsExpected(st)) AirportAnimationTrigger(Station::From(st), AAT_STATION_250_TICKS);
03595 }
03596 }
03597 }
03598
03600 void StationMonthlyLoop()
03601 {
03602 Station *st;
03603
03604 FOR_ALL_STATIONS(st) {
03605 for (CargoID i = 0; i < NUM_CARGO; i++) {
03606 GoodsEntry *ge = &st->goods[i];
03607 SB(ge->acceptance_pickup, GoodsEntry::GES_LAST_MONTH, 1, GB(ge->acceptance_pickup, GoodsEntry::GES_CURRENT_MONTH, 1));
03608 ClrBit(ge->acceptance_pickup, GoodsEntry::GES_CURRENT_MONTH);
03609 }
03610 }
03611 }
03612
03613
03614 void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
03615 {
03616 Station *st;
03617
03618 FOR_ALL_STATIONS(st) {
03619 if (st->owner == owner &&
03620 DistanceManhattan(tile, st->xy) <= radius) {
03621 for (CargoID i = 0; i < NUM_CARGO; i++) {
03622 GoodsEntry *ge = &st->goods[i];
03623
03624 if (ge->acceptance_pickup != 0) {
03625 ge->rating = Clamp(ge->rating + amount, 0, 255);
03626 }
03627 }
03628 }
03629 }
03630 }
03631
03632 static uint UpdateStationWaiting(Station *st, CargoID type, uint amount, SourceType source_type, SourceID source_id)
03633 {
03634
03635
03636 if (!CargoPacket::CanAllocateItem()) return 0;
03637
03638 GoodsEntry &ge = st->goods[type];
03639 amount += ge.amount_fract;
03640 ge.amount_fract = GB(amount, 0, 8);
03641
03642 amount >>= 8;
03643
03644 if (amount == 0) return 0;
03645
03646 StationID next = ge.GetVia(st->index);
03647 ge.cargo.Append(new CargoPacket(st->index, st->xy, amount, source_type, source_id), next);
03648 LinkGraph *lg = NULL;
03649 if (ge.link_graph == INVALID_LINK_GRAPH) {
03650 if (LinkGraph::CanAllocateItem()) {
03651 lg = new LinkGraph(type);
03652 LinkGraphSchedule::Instance()->Queue(lg);
03653 ge.link_graph = lg->index;
03654 ge.node = lg->AddNode(st);
03655 } else {
03656 DEBUG(misc, 0, "Can't allocate link graph");
03657 }
03658 } else {
03659 lg = LinkGraph::Get(ge.link_graph);
03660 }
03661 if (lg != NULL) (*lg)[ge.node].UpdateSupply(amount);
03662
03663 if (!ge.HasRating()) {
03664 InvalidateWindowData(WC_STATION_LIST, st->index);
03665 SetBit(ge.acceptance_pickup, GoodsEntry::GES_PICKUP);
03666 }
03667
03668 TriggerStationRandomisation(st, st->xy, SRT_NEW_CARGO, type);
03669 TriggerStationAnimation(st, st->xy, SAT_NEW_CARGO, type);
03670 AirportAnimationTrigger(st, AAT_STATION_NEW_CARGO, type);
03671
03672 SetWindowDirty(WC_STATION_VIEW, st->index);
03673 st->MarkTilesDirty(true);
03674 return amount;
03675 }
03676
03677 static bool IsUniqueStationName(const char *name)
03678 {
03679 const Station *st;
03680
03681 FOR_ALL_STATIONS(st) {
03682 if (st->name != NULL && strcmp(st->name, name) == 0) return false;
03683 }
03684
03685 return true;
03686 }
03687
03697 CommandCost CmdRenameStation(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
03698 {
03699 Station *st = Station::GetIfValid(p1);
03700 if (st == NULL) return CMD_ERROR;
03701
03702 CommandCost ret = CheckOwnership(st->owner);
03703 if (ret.Failed()) return ret;
03704
03705 bool reset = StrEmpty(text);
03706
03707 if (!reset) {
03708 if (Utf8StringLength(text) >= MAX_LENGTH_STATION_NAME_CHARS) return CMD_ERROR;
03709 if (!IsUniqueStationName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
03710 }
03711
03712 if (flags & DC_EXEC) {
03713 free(st->name);
03714 st->name = reset ? NULL : strdup(text);
03715
03716 st->UpdateVirtCoord();
03717 InvalidateWindowData(WC_STATION_LIST, st->owner, 1);
03718 }
03719
03720 return CommandCost();
03721 }
03722
03729 void FindStationsAroundTiles(const TileArea &location, StationList *stations)
03730 {
03731
03732 uint max_rad = (_settings_game.station.modified_catchment ? MAX_CATCHMENT : CA_UNMODIFIED);
03733
03734 uint x = TileX(location.tile);
03735 uint y = TileY(location.tile);
03736
03737 uint min_x = (x > max_rad) ? x - max_rad : 0;
03738 uint max_x = x + location.w + max_rad;
03739 uint min_y = (y > max_rad) ? y - max_rad : 0;
03740 uint max_y = y + location.h + max_rad;
03741
03742 if (min_x == 0 && _settings_game.construction.freeform_edges) min_x = 1;
03743 if (min_y == 0 && _settings_game.construction.freeform_edges) min_y = 1;
03744 if (max_x >= MapSizeX()) max_x = MapSizeX() - 1;
03745 if (max_y >= MapSizeY()) max_y = MapSizeY() - 1;
03746
03747 for (uint cy = min_y; cy < max_y; cy++) {
03748 for (uint cx = min_x; cx < max_x; cx++) {
03749 TileIndex cur_tile = TileXY(cx, cy);
03750 if (!IsTileType(cur_tile, MP_STATION)) continue;
03751
03752 Station *st = Station::GetByTile(cur_tile);
03753
03754 if (st == NULL) continue;
03755
03756 if (_settings_game.station.modified_catchment) {
03757 int rad = st->GetCatchmentRadius();
03758 int rad_x = cx - x;
03759 int rad_y = cy - y;
03760
03761 if (rad_x < -rad || rad_x >= rad + location.w) continue;
03762 if (rad_y < -rad || rad_y >= rad + location.h) continue;
03763 }
03764
03765
03766
03767
03768 stations->Include(st);
03769 }
03770 }
03771 }
03772
03777 const StationList *StationFinder::GetStations()
03778 {
03779 if (this->tile != INVALID_TILE) {
03780 FindStationsAroundTiles(*this, &this->stations);
03781 this->tile = INVALID_TILE;
03782 }
03783 return &this->stations;
03784 }
03785
03786 uint MoveGoodsToStation(CargoID type, uint amount, SourceType source_type, SourceID source_id, const StationList *all_stations)
03787 {
03788
03789 if (amount == 0) return 0;
03790
03791 Station *st1 = NULL;
03792 Station *st2 = NULL;
03793 uint best_rating1 = 0;
03794 uint best_rating2 = 0;
03795
03796 for (Station * const *st_iter = all_stations->Begin(); st_iter != all_stations->End(); ++st_iter) {
03797 Station *st = *st_iter;
03798
03799
03800 if (st->town->exclusive_counter > 0 && st->town->exclusivity != st->owner) continue;
03801
03802 if (st->goods[type].rating == 0) continue;
03803
03804 if (_settings_game.order.selectgoods && !st->goods[type].HasVehicleEverTriedLoading()) continue;
03805
03806 if (IsCargoInClass(type, CC_PASSENGERS)) {
03807 if (st->facilities == FACIL_TRUCK_STOP) continue;
03808 } else {
03809 if (st->facilities == FACIL_BUS_STOP) continue;
03810 }
03811
03812
03813 if (st1 == NULL || st->goods[type].rating >= best_rating1) {
03814 st2 = st1; best_rating2 = best_rating1; st1 = st; best_rating1 = st->goods[type].rating;
03815 } else if (st2 == NULL || st->goods[type].rating >= best_rating2) {
03816 st2 = st; best_rating2 = st->goods[type].rating;
03817 }
03818 }
03819
03820
03821 if (st1 == NULL) return 0;
03822
03823
03824
03825 amount *= best_rating1 + 1;
03826
03827 if (st2 == NULL) {
03828
03829 return UpdateStationWaiting(st1, type, amount, source_type, source_id);
03830 }
03831
03832
03833 assert(st1 != NULL);
03834 assert(st2 != NULL);
03835 assert(best_rating1 != 0 || best_rating2 != 0);
03836
03837
03838
03839
03840
03841
03842 uint worst_cargo = amount * best_rating2 / (best_rating1 + best_rating2);
03843 assert(worst_cargo <= (amount - worst_cargo));
03844
03845
03846 uint moved = UpdateStationWaiting(st1, type, amount - worst_cargo, source_type, source_id);
03847
03848
03849 return moved + UpdateStationWaiting(st2, type, worst_cargo, source_type, source_id);
03850 }
03851
03852 void BuildOilRig(TileIndex tile)
03853 {
03854 if (!Station::CanAllocateItem()) {
03855 DEBUG(misc, 0, "Can't allocate station for oilrig at 0x%X, reverting to oilrig only", tile);
03856 return;
03857 }
03858
03859 Station *st = new Station(tile);
03860 st->town = ClosestTownFromTile(tile, UINT_MAX);
03861
03862 st->string_id = GenerateStationName(st, tile, STATIONNAMING_OILRIG);
03863
03864 assert(IsTileType(tile, MP_INDUSTRY));
03865 DeleteAnimatedTile(tile);
03866 MakeOilrig(tile, st->index, GetWaterClass(tile));
03867
03868 st->owner = OWNER_NONE;
03869 st->airport.type = AT_OILRIG;
03870 st->airport.Add(tile);
03871 st->dock_tile = tile;
03872 st->facilities = FACIL_AIRPORT | FACIL_DOCK;
03873 st->build_date = _date;
03874
03875 st->rect.BeforeAddTile(tile, StationRect::ADD_FORCE);
03876
03877 st->UpdateVirtCoord();
03878 UpdateStationAcceptance(st, false);
03879 st->RecomputeIndustriesNear();
03880 }
03881
03882 void DeleteOilRig(TileIndex tile)
03883 {
03884 Station *st = Station::GetByTile(tile);
03885
03886 MakeWaterKeepingClass(tile, OWNER_NONE);
03887
03888 st->dock_tile = INVALID_TILE;
03889 st->airport.Clear();
03890 st->facilities &= ~(FACIL_AIRPORT | FACIL_DOCK);
03891 st->airport.flags = 0;
03892
03893 st->rect.AfterRemoveTile(st, tile);
03894
03895 st->UpdateVirtCoord();
03896 st->RecomputeIndustriesNear();
03897 if (!st->IsInUse()) delete st;
03898 }
03899
03900 static void ChangeTileOwner_Station(TileIndex tile, Owner old_owner, Owner new_owner)
03901 {
03902 if (IsRoadStopTile(tile)) {
03903 for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
03904
03905 if (GetRoadOwner(tile, rt) == old_owner) {
03906 if (HasTileRoadType(tile, rt)) {
03907
03908 Company::Get(old_owner)->infrastructure.road[rt] -= 2;
03909 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.road[rt] += 2;
03910 }
03911 SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
03912 }
03913 }
03914 }
03915
03916 if (!IsTileOwner(tile, old_owner)) return;
03917
03918 if (new_owner != INVALID_OWNER) {
03919
03920
03921
03922
03923 Company *old_company = Company::Get(old_owner);
03924 Company *new_company = Company::Get(new_owner);
03925
03926
03927 switch (GetStationType(tile)) {
03928 case STATION_RAIL:
03929 case STATION_WAYPOINT:
03930 if (!IsStationTileBlocked(tile)) {
03931 old_company->infrastructure.rail[GetRailType(tile)]--;
03932 new_company->infrastructure.rail[GetRailType(tile)]++;
03933 }
03934 break;
03935
03936 case STATION_BUS:
03937 case STATION_TRUCK:
03938
03939 break;
03940
03941 case STATION_BUOY:
03942 case STATION_DOCK:
03943 if (GetWaterClass(tile) == WATER_CLASS_CANAL) {
03944 old_company->infrastructure.water--;
03945 new_company->infrastructure.water++;
03946 }
03947 break;
03948
03949 default:
03950 break;
03951 }
03952
03953
03954 if (!IsBuoy(tile) && !IsAirport(tile)) {
03955 old_company->infrastructure.station--;
03956 new_company->infrastructure.station++;
03957 }
03958
03959
03960 SetTileOwner(tile, new_owner);
03961 InvalidateWindowClassesData(WC_STATION_LIST, 0);
03962 } else {
03963 if (IsDriveThroughStopTile(tile)) {
03964
03965 DoCommand(tile, 1 | 1 << 8, (GetStationType(tile) == STATION_TRUCK) ? ROADSTOP_TRUCK : ROADSTOP_BUS, DC_EXEC | DC_BANKRUPT, CMD_REMOVE_ROAD_STOP);
03966 assert(IsTileType(tile, MP_ROAD));
03967
03968 ChangeTileOwner(tile, old_owner, new_owner);
03969 } else {
03970 DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
03971
03972
03973
03974 if ((IsTileType(tile, MP_WATER) || IsBuoyTile(tile)) && IsTileOwner(tile, old_owner)) SetTileOwner(tile, OWNER_NONE);
03975 }
03976 }
03977 }
03978
03987 static bool CanRemoveRoadWithStop(TileIndex tile, DoCommandFlag flags)
03988 {
03989
03990 if (_current_company == OWNER_WATER) return true;
03991
03992 RoadTypes rts = GetRoadTypes(tile);
03993 if (HasBit(rts, ROADTYPE_TRAM)) {
03994 Owner tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
03995 if (tram_owner != OWNER_NONE && CheckOwnership(tram_owner).Failed()) return false;
03996 }
03997 if (HasBit(rts, ROADTYPE_ROAD)) {
03998 Owner road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
03999 if (road_owner != OWNER_TOWN) {
04000 if (road_owner != OWNER_NONE && CheckOwnership(road_owner).Failed()) return false;
04001 } else {
04002 if (CheckAllowRemoveRoad(tile, GetAnyRoadBits(tile, ROADTYPE_ROAD), OWNER_TOWN, ROADTYPE_ROAD, flags).Failed()) return false;
04003 }
04004 }
04005
04006 return true;
04007 }
04008
04015 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags)
04016 {
04017 if (flags & DC_AUTO) {
04018 switch (GetStationType(tile)) {
04019 default: break;
04020 case STATION_RAIL: return_cmd_error(STR_ERROR_MUST_DEMOLISH_RAILROAD);
04021 case STATION_WAYPOINT: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
04022 case STATION_AIRPORT: return_cmd_error(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST);
04023 case STATION_TRUCK: return_cmd_error(HasTileRoadType(tile, ROADTYPE_TRAM) ? STR_ERROR_MUST_DEMOLISH_CARGO_TRAM_STATION_FIRST : STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
04024 case STATION_BUS: return_cmd_error(HasTileRoadType(tile, ROADTYPE_TRAM) ? STR_ERROR_MUST_DEMOLISH_PASSENGER_TRAM_STATION_FIRST : STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
04025 case STATION_BUOY: return_cmd_error(STR_ERROR_BUOY_IN_THE_WAY);
04026 case STATION_DOCK: return_cmd_error(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST);
04027 case STATION_OILRIG:
04028 SetDParam(1, STR_INDUSTRY_NAME_OIL_RIG);
04029 return_cmd_error(STR_ERROR_GENERIC_OBJECT_IN_THE_WAY);
04030 }
04031 }
04032
04033 switch (GetStationType(tile)) {
04034 case STATION_RAIL: return RemoveRailStation(tile, flags);
04035 case STATION_WAYPOINT: return RemoveRailWaypoint(tile, flags);
04036 case STATION_AIRPORT: return RemoveAirport(tile, flags);
04037 case STATION_TRUCK:
04038 if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
04039 return_cmd_error(STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
04040 }
04041 return RemoveRoadStop(tile, flags);
04042 case STATION_BUS:
04043 if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
04044 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
04045 }
04046 return RemoveRoadStop(tile, flags);
04047 case STATION_BUOY: return RemoveBuoy(tile, flags);
04048 case STATION_DOCK: return RemoveDock(tile, flags);
04049 default: break;
04050 }
04051
04052 return CMD_ERROR;
04053 }
04054
04055 static CommandCost TerraformTile_Station(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
04056 {
04057 if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
04058
04059
04060
04061 if (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new)) {
04062 switch (GetStationType(tile)) {
04063 case STATION_WAYPOINT:
04064 case STATION_RAIL: {
04065 DiagDirection direction = AxisToDiagDir(GetRailStationAxis(tile));
04066 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
04067 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
04068 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
04069 }
04070
04071 case STATION_AIRPORT:
04072 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
04073
04074 case STATION_TRUCK:
04075 case STATION_BUS: {
04076 DiagDirection direction = GetRoadStopDir(tile);
04077 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
04078 if (IsDriveThroughStopTile(tile)) {
04079 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
04080 }
04081 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
04082 }
04083
04084 default: break;
04085 }
04086 }
04087 }
04088 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
04089 }
04090
04096 uint FlowStat::GetShare(StationID st) const
04097 {
04098 uint32 prev = 0;
04099 for (SharesMap::const_iterator it = this->shares.begin(); it != this->shares.end(); ++it) {
04100 if (it->second == st) {
04101 return it->first - prev;
04102 } else {
04103 prev = it->first;
04104 }
04105 }
04106 return 0;
04107 }
04108
04115 StationID FlowStat::GetVia(StationID excluded, StationID excluded2) const
04116 {
04117 if (this->unrestricted == 0) return INVALID_STATION;
04118 assert(!this->shares.empty());
04119 SharesMap::const_iterator it = this->shares.upper_bound(RandomRange(this->unrestricted));
04120 assert(it != this->shares.end() && it->first <= this->unrestricted);
04121 if (it->second != excluded && it->second != excluded2) return it->second;
04122
04123
04124
04125
04126 uint end = it->first;
04127 uint begin = (it == this->shares.begin() ? 0 : (--it)->first);
04128 uint interval = end - begin;
04129 if (interval >= this->unrestricted) return INVALID_STATION;
04130 uint new_max = this->unrestricted - interval;
04131 uint rand = RandomRange(new_max);
04132 SharesMap::const_iterator it2 = (rand < begin) ? this->shares.upper_bound(rand) :
04133 this->shares.upper_bound(rand + interval);
04134 assert(it2 != this->shares.end() && it2->first <= this->unrestricted);
04135 if (it2->second != excluded && it2->second != excluded2) return it2->second;
04136
04137
04138
04139
04140 uint end2 = it2->first;
04141 uint begin2 = (it2 == this->shares.begin() ? 0 : (--it2)->first);
04142 uint interval2 = end2 - begin2;
04143 if (interval2 >= new_max) return INVALID_STATION;
04144 new_max -= interval2;
04145 if (begin > begin2) {
04146 Swap(begin, begin2);
04147 Swap(end, end2);
04148 Swap(interval, interval2);
04149 }
04150 rand = RandomRange(new_max);
04151 SharesMap::const_iterator it3 = this->shares.upper_bound(this->unrestricted);
04152 if (rand < begin) {
04153 it3 = this->shares.upper_bound(rand);
04154 } else if (rand < begin2 - interval) {
04155 it3 = this->shares.upper_bound(rand + interval);
04156 } else {
04157 it3 = this->shares.upper_bound(rand + interval + interval2);
04158 }
04159 assert(it3 != this->shares.end() && it3->first <= this->unrestricted);
04160 return it3->second;
04161 }
04162
04168 void FlowStat::Invalidate()
04169 {
04170 assert(!this->shares.empty());
04171 SharesMap new_shares;
04172 uint i = 0;
04173 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
04174 new_shares[++i] = it->second;
04175 if (it->first == this->unrestricted) this->unrestricted = i;
04176 }
04177 this->shares.swap(new_shares);
04178 assert(!this->shares.empty() && this->unrestricted <= (--this->shares.end())->first);
04179 }
04180
04187 void FlowStat::ChangeShare(StationID st, int flow)
04188 {
04189
04190
04191 assert(!this->shares.empty());
04192
04193 uint removed_shares = 0;
04194 uint added_shares = 0;
04195 uint last_share = 0;
04196 SharesMap new_shares;
04197 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
04198 if (it->second == st) {
04199 if (flow < 0) {
04200 uint share = it->first - last_share;
04201 if (flow == INT_MIN || (uint)(-flow) >= share) {
04202 removed_shares += share;
04203 if (it->first <= this->unrestricted) this->unrestricted -= share;
04204 if (flow != INT_MIN) flow += share;
04205 last_share = it->first;
04206 continue;
04207 }
04208 removed_shares += (uint)(-flow);
04209 } else {
04210 added_shares += (uint)(flow);
04211 }
04212 if (it->first <= this->unrestricted) this->unrestricted += flow;
04213
04214
04215
04216 flow = 0;
04217 }
04218 new_shares[it->first + added_shares - removed_shares] = it->second;
04219 last_share = it->first;
04220 }
04221 if (flow > 0) {
04222 new_shares[last_share + (uint)flow] = st;
04223 if (this->unrestricted < last_share) {
04224 this->ReleaseShare(st);
04225 } else {
04226 this->unrestricted += flow;
04227 }
04228 }
04229 this->shares.swap(new_shares);
04230 }
04231
04237 void FlowStat::RestrictShare(StationID st)
04238 {
04239 assert(!this->shares.empty());
04240 uint flow = 0;
04241 uint last_share = 0;
04242 SharesMap new_shares;
04243 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
04244 if (flow == 0) {
04245 if (it->first > this->unrestricted) return;
04246 if (it->second == st) {
04247 flow = it->first - last_share;
04248 this->unrestricted -= flow;
04249 } else {
04250 new_shares[it->first] = it->second;
04251 }
04252 } else {
04253 new_shares[it->first - flow] = it->second;
04254 }
04255 last_share = it->first;
04256 }
04257 if (flow == 0) return;
04258 new_shares[last_share + flow] = st;
04259 this->shares.swap(new_shares);
04260 assert(!this->shares.empty());
04261 }
04262
04268 void FlowStat::ReleaseShare(StationID st)
04269 {
04270 assert(!this->shares.empty());
04271 uint flow = 0;
04272 uint next_share = 0;
04273 bool found = false;
04274 for (SharesMap::reverse_iterator it(this->shares.rbegin()); it != this->shares.rend(); ++it) {
04275 if (it->first < this->unrestricted) return;
04276 if (found) {
04277 flow = next_share - it->first;
04278 this->unrestricted += flow;
04279 break;
04280 } else {
04281 if (it->first == this->unrestricted) return;
04282 if (it->second == st) found = true;
04283 }
04284 next_share = it->first;
04285 }
04286 if (flow == 0) return;
04287 SharesMap new_shares;
04288 new_shares[flow] = st;
04289 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
04290 if (it->second != st) {
04291 new_shares[flow + it->first] = it->second;
04292 } else {
04293 flow = 0;
04294 }
04295 }
04296 this->shares.swap(new_shares);
04297 assert(!this->shares.empty());
04298 }
04299
04304 void FlowStat::ScaleToMonthly(uint runtime)
04305 {
04306 SharesMap new_shares;
04307 uint share = 0;
04308 for (SharesMap::iterator i = this->shares.begin(); i != this->shares.end(); ++i) {
04309 share = max(share + 1, i->first * 30 / runtime);
04310 new_shares[share] = i->second;
04311 if (this->unrestricted == i->first) this->unrestricted = share;
04312 }
04313 this->shares.swap(new_shares);
04314 }
04315
04322 void FlowStatMap::AddFlow(StationID origin, StationID via, uint flow)
04323 {
04324 FlowStatMap::iterator origin_it = this->find(origin);
04325 if (origin_it == this->end()) {
04326 this->insert(std::make_pair(origin, FlowStat(via, flow)));
04327 } else {
04328 origin_it->second.ChangeShare(via, flow);
04329 assert(!origin_it->second.GetShares()->empty());
04330 }
04331 }
04332
04341 void FlowStatMap::PassOnFlow(StationID origin, StationID via, uint flow)
04342 {
04343 FlowStatMap::iterator prev_it = this->find(origin);
04344 if (prev_it == this->end()) {
04345 FlowStat fs(via, flow);
04346 fs.AppendShare(INVALID_STATION, flow);
04347 this->insert(std::make_pair(origin, fs));
04348 } else {
04349 prev_it->second.ChangeShare(via, flow);
04350 prev_it->second.ChangeShare(INVALID_STATION, flow);
04351 assert(!prev_it->second.GetShares()->empty());
04352 }
04353 }
04354
04359 void FlowStatMap::FinalizeLocalConsumption(StationID self)
04360 {
04361 for (FlowStatMap::iterator i = this->begin(); i != this->end(); ++i) {
04362 FlowStat &fs = i->second;
04363 uint local = fs.GetShare(INVALID_STATION);
04364 if (local > INT_MAX) {
04365 fs.ChangeShare(self, -INT_MAX);
04366 fs.ChangeShare(INVALID_STATION, -INT_MAX);
04367 local -= INT_MAX;
04368 }
04369 fs.ChangeShare(self, -(int)local);
04370 fs.ChangeShare(INVALID_STATION, -(int)local);
04371
04372
04373
04374 assert(!fs.GetShares()->empty());
04375 }
04376 }
04377
04384 StationIDStack FlowStatMap::DeleteFlows(StationID via)
04385 {
04386 StationIDStack ret;
04387 for (FlowStatMap::iterator f_it = this->begin(); f_it != this->end();) {
04388 FlowStat &s_flows = f_it->second;
04389 s_flows.ChangeShare(via, INT_MIN);
04390 if (s_flows.GetShares()->empty()) {
04391 ret.Push(f_it->first);
04392 this->erase(f_it++);
04393 } else {
04394 ++f_it;
04395 }
04396 }
04397 return ret;
04398 }
04399
04404 void FlowStatMap::RestrictFlows(StationID via)
04405 {
04406 for (FlowStatMap::iterator it = this->begin(); it != this->end(); ++it) {
04407 it->second.RestrictShare(via);
04408 }
04409 }
04410
04415 void FlowStatMap::ReleaseFlows(StationID via)
04416 {
04417 for (FlowStatMap::iterator it = this->begin(); it != this->end(); ++it) {
04418 it->second.ReleaseShare(via);
04419 }
04420 }
04421
04427 uint GoodsEntry::GetSumFlowVia(StationID via) const
04428 {
04429 uint ret = 0;
04430 for (FlowStatMap::const_iterator i = this->flows.begin(); i != this->flows.end(); ++i) {
04431 ret += i->second.GetShare(via);
04432 }
04433 return ret;
04434 }
04435
04436 extern const TileTypeProcs _tile_type_station_procs = {
04437 DrawTile_Station,
04438 GetSlopePixelZ_Station,
04439 ClearTile_Station,
04440 NULL,
04441 GetTileDesc_Station,
04442 GetTileTrackStatus_Station,
04443 ClickTile_Station,
04444 AnimateTile_Station,
04445 TileLoop_Station,
04446 ChangeTileOwner_Station,
04447 NULL,
04448 VehicleEnter_Station,
04449 GetFoundation_Station,
04450 TerraformTile_Station,
04451 };