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