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 "widgets/station_widget.h"
00054
00055 #include "table/strings.h"
00056
00063 bool IsHangar(TileIndex t)
00064 {
00065 assert(IsTileType(t, MP_STATION));
00066
00067
00068 if (!IsAirport(t)) return false;
00069
00070 const Station *st = Station::GetByTile(t);
00071 const AirportSpec *as = st->airport.GetSpec();
00072
00073 for (uint i = 0; i < as->nof_depots; i++) {
00074 if (st->airport.GetHangarTile(i) == t) return true;
00075 }
00076
00077 return false;
00078 }
00079
00087 template <class T>
00088 CommandCost GetStationAround(TileArea ta, StationID closest_station, T **st)
00089 {
00090 ta.tile -= TileDiffXY(1, 1);
00091 ta.w += 2;
00092 ta.h += 2;
00093
00094
00095 TILE_AREA_LOOP(tile_cur, ta) {
00096 if (IsTileType(tile_cur, MP_STATION)) {
00097 StationID t = GetStationIndex(tile_cur);
00098 if (!T::IsValidID(t)) continue;
00099
00100 if (closest_station == INVALID_STATION) {
00101 closest_station = t;
00102 } else if (closest_station != t) {
00103 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
00104 }
00105 }
00106 }
00107 *st = (closest_station == INVALID_STATION) ? NULL : T::Get(closest_station);
00108 return CommandCost();
00109 }
00110
00116 typedef bool (*CMSAMatcher)(TileIndex tile);
00117
00124 static int CountMapSquareAround(TileIndex tile, CMSAMatcher cmp)
00125 {
00126 int num = 0;
00127
00128 for (int dx = -3; dx <= 3; dx++) {
00129 for (int dy = -3; dy <= 3; dy++) {
00130 TileIndex t = TileAddWrap(tile, dx, dy);
00131 if (t != INVALID_TILE && cmp(t)) num++;
00132 }
00133 }
00134
00135 return num;
00136 }
00137
00143 static bool CMSAMine(TileIndex tile)
00144 {
00145
00146 if (!IsTileType(tile, MP_INDUSTRY)) return false;
00147
00148 const Industry *ind = Industry::GetByTile(tile);
00149
00150
00151 if ((GetIndustrySpec(ind->type)->life_type & INDUSTRYLIFE_EXTRACTIVE) == 0) return false;
00152
00153 for (uint i = 0; i < lengthof(ind->produced_cargo); i++) {
00154
00155
00156 if (ind->produced_cargo[i] != CT_INVALID &&
00157 (CargoSpec::Get(ind->produced_cargo[i])->classes & (CC_LIQUID | CC_PASSENGERS | CC_MAIL)) == 0) {
00158 return true;
00159 }
00160 }
00161
00162 return false;
00163 }
00164
00170 static bool CMSAWater(TileIndex tile)
00171 {
00172 return IsTileType(tile, MP_WATER) && IsWater(tile);
00173 }
00174
00180 static bool CMSATree(TileIndex tile)
00181 {
00182 return IsTileType(tile, MP_TREES);
00183 }
00184
00185 #define M(x) ((x) - STR_SV_STNAME)
00186
00187 enum StationNaming {
00188 STATIONNAMING_RAIL,
00189 STATIONNAMING_ROAD,
00190 STATIONNAMING_AIRPORT,
00191 STATIONNAMING_OILRIG,
00192 STATIONNAMING_DOCK,
00193 STATIONNAMING_HELIPORT,
00194 };
00195
00197 struct StationNameInformation {
00198 uint32 free_names;
00199 bool *indtypes;
00200 };
00201
00210 static bool FindNearIndustryName(TileIndex tile, void *user_data)
00211 {
00212
00213 StationNameInformation *sni = (StationNameInformation*)user_data;
00214 if (!IsTileType(tile, MP_INDUSTRY)) return false;
00215
00216
00217 IndustryType indtype = GetIndustryType(tile);
00218 if (GetIndustrySpec(indtype)->station_name == STR_UNDEFINED) return false;
00219
00220
00221
00222 sni->free_names &= ~(1 << M(STR_SV_STNAME_OILFIELD) | 1 << M(STR_SV_STNAME_MINES));
00223 return !sni->indtypes[indtype];
00224 }
00225
00226 static StringID GenerateStationName(Station *st, TileIndex tile, StationNaming name_class)
00227 {
00228 static const uint32 _gen_station_name_bits[] = {
00229 0,
00230 0,
00231 1U << M(STR_SV_STNAME_AIRPORT),
00232 1U << M(STR_SV_STNAME_OILFIELD),
00233 1U << M(STR_SV_STNAME_DOCKS),
00234 1U << M(STR_SV_STNAME_HELIPORT),
00235 };
00236
00237 const Town *t = st->town;
00238 uint32 free_names = UINT32_MAX;
00239
00240 bool indtypes[NUM_INDUSTRYTYPES];
00241 memset(indtypes, 0, sizeof(indtypes));
00242
00243 const Station *s;
00244 FOR_ALL_STATIONS(s) {
00245 if (s != st && s->town == t) {
00246 if (s->indtype != IT_INVALID) {
00247 indtypes[s->indtype] = true;
00248 continue;
00249 }
00250 uint str = M(s->string_id);
00251 if (str <= 0x20) {
00252 if (str == M(STR_SV_STNAME_FOREST)) {
00253 str = M(STR_SV_STNAME_WOODS);
00254 }
00255 ClrBit(free_names, str);
00256 }
00257 }
00258 }
00259
00260 TileIndex indtile = tile;
00261 StationNameInformation sni = { free_names, indtypes };
00262 if (CircularTileSearch(&indtile, 7, FindNearIndustryName, &sni)) {
00263
00264 IndustryType indtype = GetIndustryType(indtile);
00265 const IndustrySpec *indsp = GetIndustrySpec(indtype);
00266
00267 if (indsp->station_name != STR_NULL) {
00268 st->indtype = indtype;
00269 return STR_SV_STNAME_FALLBACK;
00270 }
00271 }
00272
00273
00274 free_names = sni.free_names;
00275
00276
00277 uint32 tmp = free_names & _gen_station_name_bits[name_class];
00278 if (tmp != 0) return STR_SV_STNAME + FindFirstBit(tmp);
00279
00280
00281 if (HasBit(free_names, M(STR_SV_STNAME_MINES))) {
00282 if (CountMapSquareAround(tile, CMSAMine) >= 2) {
00283 return STR_SV_STNAME_MINES;
00284 }
00285 }
00286
00287
00288 if (DistanceMax(tile, t->xy) < 8) {
00289 if (HasBit(free_names, M(STR_SV_STNAME))) return STR_SV_STNAME;
00290
00291 if (HasBit(free_names, M(STR_SV_STNAME_CENTRAL))) return STR_SV_STNAME_CENTRAL;
00292 }
00293
00294
00295 if (HasBit(free_names, M(STR_SV_STNAME_LAKESIDE)) &&
00296 DistanceFromEdge(tile) < 20 &&
00297 CountMapSquareAround(tile, CMSAWater) >= 5) {
00298 return STR_SV_STNAME_LAKESIDE;
00299 }
00300
00301
00302 if (HasBit(free_names, M(STR_SV_STNAME_WOODS)) && (
00303 CountMapSquareAround(tile, CMSATree) >= 8 ||
00304 CountMapSquareAround(tile, IsTileForestIndustry) >= 2)
00305 ) {
00306 return _settings_game.game_creation.landscape == LT_TROPIC ? STR_SV_STNAME_FOREST : STR_SV_STNAME_WOODS;
00307 }
00308
00309
00310 int z = GetTileZ(tile);
00311 int z2 = GetTileZ(t->xy);
00312 if (z < z2) {
00313 if (HasBit(free_names, M(STR_SV_STNAME_VALLEY))) return STR_SV_STNAME_VALLEY;
00314 } else if (z > z2) {
00315 if (HasBit(free_names, M(STR_SV_STNAME_HEIGHTS))) return STR_SV_STNAME_HEIGHTS;
00316 }
00317
00318
00319 static const int8 _direction_and_table[] = {
00320 ~( (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
00321 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
00322 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (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_EAST)) ),
00324 };
00325
00326 free_names &= _direction_and_table[
00327 (TileX(tile) < TileX(t->xy)) +
00328 (TileY(tile) < TileY(t->xy)) * 2];
00329
00330 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));
00331 return (tmp == 0) ? STR_SV_STNAME_FALLBACK : (STR_SV_STNAME + FindFirstBit(tmp));
00332 }
00333 #undef M
00334
00340 static Station *GetClosestDeletedStation(TileIndex tile)
00341 {
00342 uint threshold = 8;
00343 Station *best_station = NULL;
00344 Station *st;
00345
00346 FOR_ALL_STATIONS(st) {
00347 if (!st->IsInUse() && st->owner == _current_company) {
00348 uint cur_dist = DistanceManhattan(tile, st->xy);
00349
00350 if (cur_dist < threshold) {
00351 threshold = cur_dist;
00352 best_station = st;
00353 }
00354 }
00355 }
00356
00357 return best_station;
00358 }
00359
00360
00361 void Station::GetTileArea(TileArea *ta, StationType type) const
00362 {
00363 switch (type) {
00364 case STATION_RAIL:
00365 *ta = this->train_station;
00366 return;
00367
00368 case STATION_AIRPORT:
00369 *ta = this->airport;
00370 return;
00371
00372 case STATION_TRUCK:
00373 *ta = this->truck_station;
00374 return;
00375
00376 case STATION_BUS:
00377 *ta = this->bus_station;
00378 return;
00379
00380 case STATION_DOCK:
00381 case STATION_OILRIG:
00382 ta->tile = this->dock_tile;
00383 break;
00384
00385 default: NOT_REACHED();
00386 }
00387
00388 ta->w = 1;
00389 ta->h = 1;
00390 }
00391
00395 void Station::UpdateVirtCoord()
00396 {
00397 Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
00398
00399 pt.y -= 32 * ZOOM_LVL_BASE;
00400 if ((this->facilities & FACIL_AIRPORT) && this->airport.type == AT_OILRIG) pt.y -= 16 * ZOOM_LVL_BASE;
00401
00402 SetDParam(0, this->index);
00403 SetDParam(1, this->facilities);
00404 this->sign.UpdatePosition(pt.x, pt.y, STR_VIEWPORT_STATION);
00405
00406 SetWindowDirty(WC_STATION_VIEW, this->index);
00407 }
00408
00410 void UpdateAllStationVirtCoords()
00411 {
00412 BaseStation *st;
00413
00414 FOR_ALL_BASE_STATIONS(st) {
00415 st->UpdateVirtCoord();
00416 }
00417 }
00418
00424 static uint GetAcceptanceMask(const Station *st)
00425 {
00426 uint mask = 0;
00427
00428 for (CargoID i = 0; i < NUM_CARGO; i++) {
00429 if (HasBit(st->goods[i].acceptance_pickup, GoodsEntry::GES_ACCEPTANCE)) mask |= 1 << i;
00430 }
00431 return mask;
00432 }
00433
00438 static void ShowRejectOrAcceptNews(const Station *st, uint num_items, CargoID *cargo, StringID msg)
00439 {
00440 for (uint i = 0; i < num_items; i++) {
00441 SetDParam(i + 1, CargoSpec::Get(cargo[i])->name);
00442 }
00443
00444 SetDParam(0, st->index);
00445 AddNewsItem(msg, NT_ACCEPTANCE, NF_INCOLOUR | NF_SMALL, NR_STATION, st->index);
00446 }
00447
00455 CargoArray GetProductionAroundTiles(TileIndex tile, int w, int h, int rad)
00456 {
00457 CargoArray produced;
00458
00459 int x = TileX(tile);
00460 int y = TileY(tile);
00461
00462
00463
00464 int x2 = min(x + w + rad, MapSizeX());
00465 int x1 = max(x - rad, 0);
00466
00467 int y2 = min(y + h + rad, MapSizeY());
00468 int y1 = max(y - rad, 0);
00469
00470 assert(x1 < x2);
00471 assert(y1 < y2);
00472 assert(w > 0);
00473 assert(h > 0);
00474
00475 TileArea ta(TileXY(x1, y1), TileXY(x2 - 1, y2 - 1));
00476
00477
00478
00479 TILE_AREA_LOOP(tile, ta) AddProducedCargo(tile, produced);
00480
00481
00482
00483
00484
00485
00486
00487 const Industry *i;
00488 FOR_ALL_INDUSTRIES(i) {
00489 if (!ta.Intersects(i->location)) continue;
00490
00491 for (uint j = 0; j < lengthof(i->produced_cargo); j++) {
00492 CargoID cargo = i->produced_cargo[j];
00493 if (cargo != CT_INVALID) produced[cargo]++;
00494 }
00495 }
00496
00497 return produced;
00498 }
00499
00508 CargoArray GetAcceptanceAroundTiles(TileIndex tile, int w, int h, int rad, uint32 *always_accepted)
00509 {
00510 CargoArray acceptance;
00511 if (always_accepted != NULL) *always_accepted = 0;
00512
00513 int x = TileX(tile);
00514 int y = TileY(tile);
00515
00516
00517
00518 int x2 = min(x + w + rad, MapSizeX());
00519 int y2 = min(y + h + rad, MapSizeY());
00520 int x1 = max(x - rad, 0);
00521 int y1 = max(y - rad, 0);
00522
00523 assert(x1 < x2);
00524 assert(y1 < y2);
00525 assert(w > 0);
00526 assert(h > 0);
00527
00528 for (int yc = y1; yc != y2; yc++) {
00529 for (int xc = x1; xc != x2; xc++) {
00530 TileIndex tile = TileXY(xc, yc);
00531 AddAcceptedCargo(tile, acceptance, always_accepted);
00532 }
00533 }
00534
00535 return acceptance;
00536 }
00537
00543 void UpdateStationAcceptance(Station *st, bool show_msg)
00544 {
00545
00546 uint old_acc = GetAcceptanceMask(st);
00547
00548
00549 CargoArray acceptance;
00550 if (!st->rect.IsEmpty()) {
00551 acceptance = GetAcceptanceAroundTiles(
00552 TileXY(st->rect.left, st->rect.top),
00553 st->rect.right - st->rect.left + 1,
00554 st->rect.bottom - st->rect.top + 1,
00555 st->GetCatchmentRadius(),
00556 &st->always_accepted
00557 );
00558 }
00559
00560
00561 for (CargoID i = 0; i < NUM_CARGO; i++) {
00562 uint amt = min(acceptance[i], 15);
00563
00564
00565 bool is_passengers = IsCargoInClass(i, CC_PASSENGERS);
00566 if ((!is_passengers && !(st->facilities & ~FACIL_BUS_STOP)) ||
00567 (is_passengers && !(st->facilities & ~FACIL_TRUCK_STOP))) {
00568 amt = 0;
00569 }
00570
00571 SB(st->goods[i].acceptance_pickup, GoodsEntry::GES_ACCEPTANCE, 1, amt >= 8);
00572 }
00573
00574
00575 uint new_acc = GetAcceptanceMask(st);
00576 if (old_acc == new_acc) return;
00577
00578
00579 if (show_msg && st->owner == _local_company && st->IsInUse()) {
00580
00581
00582 static const StringID accept_msg[] = {
00583 STR_NEWS_STATION_NOW_ACCEPTS_CARGO,
00584 STR_NEWS_STATION_NOW_ACCEPTS_CARGO_AND_CARGO,
00585 };
00586 static const StringID reject_msg[] = {
00587 STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO,
00588 STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO_OR_CARGO,
00589 };
00590
00591
00592 CargoID accepts[2] = { CT_INVALID, CT_INVALID };
00593 CargoID rejects[2] = { CT_INVALID, CT_INVALID };
00594 uint num_acc = 0;
00595 uint num_rej = 0;
00596
00597
00598 for (CargoID i = 0; i < NUM_CARGO; i++) {
00599 if (HasBit(new_acc, i)) {
00600 if (!HasBit(old_acc, i) && num_acc < lengthof(accepts)) {
00601
00602 accepts[num_acc++] = i;
00603 }
00604 } else {
00605 if (HasBit(old_acc, i) && num_rej < lengthof(rejects)) {
00606
00607 rejects[num_rej++] = i;
00608 }
00609 }
00610 }
00611
00612
00613 if (num_acc > 0) ShowRejectOrAcceptNews(st, num_acc, accepts, accept_msg[num_acc - 1]);
00614 if (num_rej > 0) ShowRejectOrAcceptNews(st, num_rej, rejects, reject_msg[num_rej - 1]);
00615 }
00616
00617
00618 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ACCEPT_RATING_LIST);
00619 }
00620
00621 static void UpdateStationSignCoord(BaseStation *st)
00622 {
00623 const StationRect *r = &st->rect;
00624
00625 if (r->IsEmpty()) return;
00626
00627
00628 st->xy = TileXY(ClampU(TileX(st->xy), r->left, r->right), ClampU(TileY(st->xy), r->top, r->bottom));
00629 st->UpdateVirtCoord();
00630 }
00631
00641 static CommandCost BuildStationPart(Station **st, DoCommandFlag flags, bool reuse, TileArea area, StationNaming name_class)
00642 {
00643
00644 if (*st == NULL && reuse) *st = GetClosestDeletedStation(area.tile);
00645
00646 if (*st != NULL) {
00647 if ((*st)->owner != _current_company) {
00648 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
00649 }
00650
00651 CommandCost ret = (*st)->rect.BeforeAddRect(area.tile, area.w, area.h, StationRect::ADD_TEST);
00652 if (ret.Failed()) return ret;
00653 } else {
00654
00655 if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
00656
00657 if (flags & DC_EXEC) {
00658 *st = new Station(area.tile);
00659
00660 (*st)->town = ClosestTownFromTile(area.tile, UINT_MAX);
00661 (*st)->string_id = GenerateStationName(*st, area.tile, name_class);
00662
00663 if (Company::IsValidID(_current_company)) {
00664 SetBit((*st)->town->have_ratings, _current_company);
00665 }
00666 }
00667 }
00668 return CommandCost();
00669 }
00670
00677 static void DeleteStationIfEmpty(BaseStation *st)
00678 {
00679 if (!st->IsInUse()) {
00680 st->delete_ctr = 0;
00681 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
00682 }
00683
00684 UpdateStationSignCoord(st);
00685 }
00686
00687 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags);
00688
00698 CommandCost CheckBuildableTile(TileIndex tile, uint invalid_dirs, int &allowed_z, bool allow_steep, bool check_bridge = true)
00699 {
00700 if (check_bridge && MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) {
00701 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00702 }
00703
00704 CommandCost ret = EnsureNoVehicleOnGround(tile);
00705 if (ret.Failed()) return ret;
00706
00707 int z;
00708 Slope tileh = GetTileSlope(tile, &z);
00709
00710
00711
00712
00713
00714 if ((!allow_steep && IsSteepSlope(tileh)) ||
00715 ((!_settings_game.construction.build_on_slopes) && tileh != SLOPE_FLAT)) {
00716 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00717 }
00718
00719 CommandCost cost(EXPENSES_CONSTRUCTION);
00720 int flat_z = z + GetSlopeMaxZ(tileh);
00721 if (tileh != SLOPE_FLAT) {
00722
00723 for (DiagDirection dir = DIAGDIR_BEGIN; dir != DIAGDIR_END; dir++) {
00724 if (HasBit(invalid_dirs, dir) && !CanBuildDepotByTileh(dir, tileh)) {
00725 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00726 }
00727 }
00728 cost.AddCost(_price[PR_BUILD_FOUNDATION]);
00729 }
00730
00731
00732 if (allowed_z < 0) {
00733
00734 allowed_z = flat_z;
00735 } else if (allowed_z != flat_z) {
00736 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00737 }
00738
00739 return cost;
00740 }
00741
00748 CommandCost CheckFlatLand(TileArea tile_area, DoCommandFlag flags)
00749 {
00750 CommandCost cost(EXPENSES_CONSTRUCTION);
00751 int allowed_z = -1;
00752
00753 TILE_AREA_LOOP(tile_cur, tile_area) {
00754 CommandCost ret = CheckBuildableTile(tile_cur, 0, allowed_z, true);
00755 if (ret.Failed()) return ret;
00756 cost.AddCost(ret);
00757
00758 ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00759 if (ret.Failed()) return ret;
00760 cost.AddCost(ret);
00761 }
00762
00763 return cost;
00764 }
00765
00780 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)
00781 {
00782 CommandCost cost(EXPENSES_CONSTRUCTION);
00783 int allowed_z = -1;
00784 uint invalid_dirs = 5 << axis;
00785
00786 const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
00787 bool slope_cb = statspec != NULL && HasBit(statspec->callback_mask, CBM_STATION_SLOPE_CHECK);
00788
00789 TILE_AREA_LOOP(tile_cur, tile_area) {
00790 CommandCost ret = CheckBuildableTile(tile_cur, invalid_dirs, allowed_z, false);
00791 if (ret.Failed()) return ret;
00792 cost.AddCost(ret);
00793
00794 if (slope_cb) {
00795
00796 ret = PerformStationTileSlopeCheck(tile_area.tile, tile_cur, statspec, axis, plat_len, numtracks);
00797 if (ret.Failed()) return ret;
00798 }
00799
00800
00801
00802
00803 if (station != NULL && IsTileType(tile_cur, MP_STATION)) {
00804 if (!IsRailStation(tile_cur)) {
00805 return ClearTile_Station(tile_cur, DC_AUTO);
00806 } else {
00807 StationID st = GetStationIndex(tile_cur);
00808 if (*station == INVALID_STATION) {
00809 *station = st;
00810 } else if (*station != st) {
00811 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
00812 }
00813 }
00814 } else {
00815
00816
00817 if (rt != INVALID_RAILTYPE &&
00818 IsPlainRailTile(tile_cur) && !HasSignals(tile_cur) &&
00819 HasPowerOnRail(GetRailType(tile_cur), rt)) {
00820
00821
00822
00823
00824
00825
00826 TrackBits tracks = GetTrackBits(tile_cur);
00827 Track track = RemoveFirstTrack(&tracks);
00828 Track expected_track = HasBit(invalid_dirs, DIAGDIR_NE) ? TRACK_X : TRACK_Y;
00829
00830 if (tracks == TRACK_BIT_NONE && track == expected_track) {
00831
00832 if (HasBit(GetRailReservationTrackBits(tile_cur), track)) {
00833 Train *v = GetTrainForReservation(tile_cur, track);
00834 if (v != NULL) {
00835 *affected_vehicles.Append() = v;
00836 }
00837 }
00838 CommandCost ret = DoCommand(tile_cur, 0, track, flags, CMD_REMOVE_SINGLE_RAIL);
00839 if (ret.Failed()) return ret;
00840 cost.AddCost(ret);
00841
00842 continue;
00843 }
00844 }
00845 ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00846 if (ret.Failed()) return ret;
00847 cost.AddCost(ret);
00848 }
00849 }
00850
00851 return cost;
00852 }
00853
00866 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)
00867 {
00868 CommandCost cost(EXPENSES_CONSTRUCTION);
00869 int allowed_z = -1;
00870
00871 TILE_AREA_LOOP(cur_tile, tile_area) {
00872 CommandCost ret = CheckBuildableTile(cur_tile, invalid_dirs, allowed_z, !is_drive_through);
00873 if (ret.Failed()) return ret;
00874 cost.AddCost(ret);
00875
00876
00877
00878
00879 if (station != NULL && IsTileType(cur_tile, MP_STATION)) {
00880 if (!IsRoadStop(cur_tile)) {
00881 return ClearTile_Station(cur_tile, DC_AUTO);
00882 } else {
00883 if (is_truck_stop != IsTruckStop(cur_tile) ||
00884 is_drive_through != IsDriveThroughStopTile(cur_tile)) {
00885 return ClearTile_Station(cur_tile, DC_AUTO);
00886 }
00887
00888 if (is_drive_through && IsDriveThroughStopTile(cur_tile) && DiagDirToAxis(GetRoadStopDir(cur_tile)) != axis){
00889 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
00890 }
00891 StationID st = GetStationIndex(cur_tile);
00892 if (*station == INVALID_STATION) {
00893 *station = st;
00894 } else if (*station != st) {
00895 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
00896 }
00897 }
00898 } else {
00899 bool build_over_road = is_drive_through && IsNormalRoadTile(cur_tile);
00900
00901 RoadBits rb = IsNormalRoadTile(cur_tile) ? GetAllRoadBits(cur_tile) : ROAD_NONE;
00902 if (build_over_road && (rb & (axis == AXIS_X ? ROAD_Y : ROAD_X)) != 0) {
00903
00904 switch (CountBits(rb)) {
00905 case 1:
00906 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
00907
00908 case 2:
00909 if (rb == ROAD_X || rb == ROAD_Y) return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
00910 return_cmd_error(STR_ERROR_DRIVE_THROUGH_CORNER);
00911
00912 default:
00913 return_cmd_error(STR_ERROR_DRIVE_THROUGH_JUNCTION);
00914 }
00915 }
00916
00917 RoadTypes cur_rts = IsNormalRoadTile(cur_tile) ? GetRoadTypes(cur_tile) : ROADTYPES_NONE;
00918 uint num_roadbits = 0;
00919 if (build_over_road) {
00920
00921 if (HasBit(cur_rts, ROADTYPE_ROAD)) {
00922 Owner road_owner = GetRoadOwner(cur_tile, ROADTYPE_ROAD);
00923 if (road_owner == OWNER_TOWN) {
00924 if (!_settings_game.construction.road_stop_on_town_road) return_cmd_error(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD);
00925 } else if (!_settings_game.construction.road_stop_on_competitor_road && road_owner != OWNER_NONE) {
00926 CommandCost ret = CheckOwnership(road_owner);
00927 if (ret.Failed()) return ret;
00928 }
00929 num_roadbits += CountBits(GetRoadBits(cur_tile, ROADTYPE_ROAD));
00930 }
00931
00932
00933 if (HasBit(cur_rts, ROADTYPE_TRAM)) {
00934 Owner tram_owner = GetRoadOwner(cur_tile, ROADTYPE_TRAM);
00935 if (!_settings_game.construction.road_stop_on_competitor_road && tram_owner != OWNER_NONE) {
00936 CommandCost ret = CheckOwnership(tram_owner);
00937 if (ret.Failed()) return ret;
00938 }
00939 num_roadbits += CountBits(GetRoadBits(cur_tile, ROADTYPE_TRAM));
00940 }
00941
00942
00943 rts |= cur_rts;
00944 } else {
00945 ret = DoCommand(cur_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00946 if (ret.Failed()) return ret;
00947 cost.AddCost(ret);
00948 }
00949
00950 uint roadbits_to_build = CountBits(rts) * 2 - num_roadbits;
00951 cost.AddCost(_price[PR_BUILD_ROAD] * roadbits_to_build);
00952 }
00953 }
00954
00955 return cost;
00956 }
00957
00965 CommandCost CanExpandRailStation(const BaseStation *st, TileArea &new_ta, Axis axis)
00966 {
00967 TileArea cur_ta = st->train_station;
00968
00969
00970 int x = min(TileX(cur_ta.tile), TileX(new_ta.tile));
00971 int y = min(TileY(cur_ta.tile), TileY(new_ta.tile));
00972 new_ta.w = max(TileX(cur_ta.tile) + cur_ta.w, TileX(new_ta.tile) + new_ta.w) - x;
00973 new_ta.h = max(TileY(cur_ta.tile) + cur_ta.h, TileY(new_ta.tile) + new_ta.h) - y;
00974 new_ta.tile = TileXY(x, y);
00975
00976
00977 if (new_ta.w > _settings_game.station.station_spread || new_ta.h > _settings_game.station.station_spread) {
00978 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
00979 }
00980
00981 return CommandCost();
00982 }
00983
00984 static inline byte *CreateSingle(byte *layout, int n)
00985 {
00986 int i = n;
00987 do *layout++ = 0; while (--i);
00988 layout[((n - 1) >> 1) - n] = 2;
00989 return layout;
00990 }
00991
00992 static inline byte *CreateMulti(byte *layout, int n, byte b)
00993 {
00994 int i = n;
00995 do *layout++ = b; while (--i);
00996 if (n > 4) {
00997 layout[0 - n] = 0;
00998 layout[n - 1 - n] = 0;
00999 }
01000 return layout;
01001 }
01002
01010 void GetStationLayout(byte *layout, int numtracks, int plat_len, const StationSpec *statspec)
01011 {
01012 if (statspec != NULL && statspec->lengths >= plat_len &&
01013 statspec->platforms[plat_len - 1] >= numtracks &&
01014 statspec->layouts[plat_len - 1][numtracks - 1]) {
01015
01016 memcpy(layout, statspec->layouts[plat_len - 1][numtracks - 1],
01017 plat_len * numtracks);
01018 return;
01019 }
01020
01021 if (plat_len == 1) {
01022 CreateSingle(layout, numtracks);
01023 } else {
01024 if (numtracks & 1) layout = CreateSingle(layout, plat_len);
01025 numtracks >>= 1;
01026
01027 while (--numtracks >= 0) {
01028 layout = CreateMulti(layout, plat_len, 4);
01029 layout = CreateMulti(layout, plat_len, 6);
01030 }
01031 }
01032 }
01033
01045 template <class T, StringID error_message>
01046 CommandCost FindJoiningBaseStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, T **st)
01047 {
01048 assert(*st == NULL);
01049 bool check_surrounding = true;
01050
01051 if (_settings_game.station.adjacent_stations) {
01052 if (existing_station != INVALID_STATION) {
01053 if (adjacent && existing_station != station_to_join) {
01054
01055
01056 return_cmd_error(error_message);
01057 } else {
01058
01059
01060 *st = T::GetIfValid(existing_station);
01061 check_surrounding = (*st == NULL);
01062 }
01063 } else {
01064
01065
01066 if (adjacent) check_surrounding = false;
01067 }
01068 }
01069
01070 if (check_surrounding) {
01071
01072 CommandCost ret = GetStationAround(ta, existing_station, st);
01073 if (ret.Failed()) return ret;
01074 }
01075
01076
01077 if (*st == NULL && station_to_join != INVALID_STATION) *st = T::GetIfValid(station_to_join);
01078
01079 return CommandCost();
01080 }
01081
01091 static CommandCost FindJoiningStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
01092 {
01093 return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_RAILWAY_STATION_FIRST>(existing_station, station_to_join, adjacent, ta, st);
01094 }
01095
01105 CommandCost FindJoiningWaypoint(StationID existing_waypoint, StationID waypoint_to_join, bool adjacent, TileArea ta, Waypoint **wp)
01106 {
01107 return FindJoiningBaseStation<Waypoint, STR_ERROR_MUST_REMOVE_RAILWAYPOINT_FIRST>(existing_waypoint, waypoint_to_join, adjacent, ta, wp);
01108 }
01109
01127 CommandCost CmdBuildRailStation(TileIndex tile_org, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01128 {
01129
01130 RailType rt = Extract<RailType, 0, 4>(p1);
01131 Axis axis = Extract<Axis, 4, 1>(p1);
01132 byte numtracks = GB(p1, 8, 8);
01133 byte plat_len = GB(p1, 16, 8);
01134 bool adjacent = HasBit(p1, 24);
01135
01136 StationClassID spec_class = Extract<StationClassID, 0, 8>(p2);
01137 byte spec_index = GB(p2, 8, 8);
01138 StationID station_to_join = GB(p2, 16, 16);
01139
01140
01141 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile_org, flags);
01142 if (ret.Failed()) return ret;
01143
01144 if (!ValParamRailtype(rt)) return CMD_ERROR;
01145
01146
01147 if ((uint)spec_class >= StationClass::GetClassCount() || spec_class == STAT_CLASS_WAYP) return CMD_ERROR;
01148 if (spec_index >= StationClass::Get(spec_class)->GetSpecCount()) return CMD_ERROR;
01149 if (plat_len == 0 || numtracks == 0) return CMD_ERROR;
01150
01151 int w_org, h_org;
01152 if (axis == AXIS_X) {
01153 w_org = plat_len;
01154 h_org = numtracks;
01155 } else {
01156 h_org = plat_len;
01157 w_org = numtracks;
01158 }
01159
01160 bool reuse = (station_to_join != NEW_STATION);
01161 if (!reuse) station_to_join = INVALID_STATION;
01162 bool distant_join = (station_to_join != INVALID_STATION);
01163
01164 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
01165
01166 if (h_org > _settings_game.station.station_spread || w_org > _settings_game.station.station_spread) return CMD_ERROR;
01167
01168
01169 TileArea new_location(tile_org, w_org, h_org);
01170
01171
01172 StationID est = INVALID_STATION;
01173 SmallVector<Train *, 4> affected_vehicles;
01174
01175 CommandCost cost = CheckFlatLandRailStation(new_location, flags, axis, &est, rt, affected_vehicles, spec_class, spec_index, plat_len, numtracks);
01176 if (cost.Failed()) return cost;
01177
01178 cost.AddCost((numtracks * _price[PR_BUILD_STATION_RAIL] + _price[PR_BUILD_STATION_RAIL_LENGTH]) * plat_len);
01179 cost.AddCost(numtracks * plat_len * RailBuildCost(rt));
01180
01181 Station *st = NULL;
01182 ret = FindJoiningStation(est, station_to_join, adjacent, new_location, &st);
01183 if (ret.Failed()) return ret;
01184
01185 ret = BuildStationPart(&st, flags, reuse, new_location, STATIONNAMING_RAIL);
01186 if (ret.Failed()) return ret;
01187
01188 if (st != NULL && st->train_station.tile != INVALID_TILE) {
01189 CommandCost ret = CanExpandRailStation(st, new_location, axis);
01190 if (ret.Failed()) return ret;
01191 }
01192
01193
01194 const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
01195 int specindex = AllocateSpecToStation(statspec, st, (flags & DC_EXEC) != 0);
01196 if (specindex == -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS);
01197
01198 if (statspec != NULL) {
01199
01200
01201
01202 if (HasBit(statspec->disallowed_platforms, numtracks - 1) || HasBit(statspec->disallowed_lengths, plat_len - 1)) {
01203 return CMD_ERROR;
01204 }
01205
01206
01207 if (HasBit(statspec->callback_mask, CBM_STATION_AVAIL)) {
01208 uint16 cb_res = GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, NULL, INVALID_TILE);
01209 if (cb_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(statspec->grf_prop.grffile, CBID_STATION_AVAILABILITY, cb_res)) return CMD_ERROR;
01210 }
01211 }
01212
01213 if (flags & DC_EXEC) {
01214 TileIndexDiff tile_delta;
01215 byte *layout_ptr;
01216 byte numtracks_orig;
01217 Track track;
01218
01219 st->train_station = new_location;
01220 st->AddFacility(FACIL_TRAIN, new_location.tile);
01221
01222 st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TRY);
01223
01224 if (statspec != NULL) {
01225
01226
01227 st->cached_anim_triggers |= statspec->animation.triggers;
01228 }
01229
01230 tile_delta = (axis == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
01231 track = AxisToTrack(axis);
01232
01233 layout_ptr = AllocaM(byte, numtracks * plat_len);
01234 GetStationLayout(layout_ptr, numtracks, plat_len, statspec);
01235
01236 numtracks_orig = numtracks;
01237
01238 Company *c = Company::Get(st->owner);
01239 do {
01240 TileIndex tile = tile_org;
01241 int w = plat_len;
01242 do {
01243 byte layout = *layout_ptr++;
01244 if (IsRailStationTile(tile) && HasStationReservation(tile)) {
01245
01246 Train *v = GetTrainForReservation(tile, AxisToTrack(GetRailStationAxis(tile)));
01247 if (v != NULL) {
01248 FreeTrainTrackReservation(v);
01249 *affected_vehicles.Append() = v;
01250 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
01251 for (; v->Next() != NULL; v = v->Next()) { }
01252 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), false);
01253 }
01254 }
01255
01256
01257 if (IsRailStationTile(tile)) {
01258 if (!IsStationTileBlocked(tile)) c->infrastructure.rail[GetRailType(tile)]--;
01259 c->infrastructure.station--;
01260 }
01261
01262
01263 DeleteAnimatedTile(tile);
01264 byte old_specindex = HasStationTileRail(tile) ? GetCustomStationSpecIndex(tile) : 0;
01265 MakeRailStation(tile, st->owner, st->index, axis, layout & ~1, rt);
01266
01267 DeallocateSpecFromStation(st, old_specindex);
01268
01269 SetCustomStationSpecIndex(tile, specindex);
01270 SetStationTileRandomBits(tile, GB(Random(), 0, 4));
01271 SetAnimationFrame(tile, 0);
01272
01273 if (!IsStationTileBlocked(tile)) c->infrastructure.rail[rt]++;
01274 c->infrastructure.station++;
01275
01276 if (statspec != NULL) {
01277
01278 uint32 platinfo = GetPlatformInfo(AXIS_X, 0, plat_len, numtracks_orig, plat_len - w, numtracks_orig - numtracks, false);
01279
01280
01281 uint16 callback = GetStationCallback(CBID_STATION_TILE_LAYOUT, platinfo, 0, statspec, NULL, tile);
01282 if (callback != CALLBACK_FAILED) {
01283 if (callback < 8) {
01284 SetStationGfx(tile, (callback & ~1) + axis);
01285 } else {
01286 ErrorUnknownCallbackResult(statspec->grf_prop.grffile->grfid, CBID_STATION_TILE_LAYOUT, callback);
01287 }
01288 }
01289
01290
01291 TriggerStationAnimation(st, tile, SAT_BUILT);
01292 }
01293
01294 tile += tile_delta;
01295 } while (--w);
01296 AddTrackToSignalBuffer(tile_org, track, _current_company);
01297 YapfNotifyTrackLayoutChange(tile_org, track);
01298 tile_org += tile_delta ^ TileDiffXY(1, 1);
01299 } while (--numtracks);
01300
01301 for (uint i = 0; i < affected_vehicles.Length(); ++i) {
01302
01303 Train *v = affected_vehicles[i];
01304 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
01305 TryPathReserve(v, true, true);
01306 for (; v->Next() != NULL; v = v->Next()) { }
01307 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
01308 }
01309
01310 st->MarkTilesDirty(false);
01311 st->UpdateVirtCoord();
01312 UpdateStationAcceptance(st, false);
01313 st->RecomputeIndustriesNear();
01314 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
01315 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
01316 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
01317 DirtyCompanyInfrastructureWindows(st->owner);
01318 }
01319
01320 return cost;
01321 }
01322
01323 static void MakeRailStationAreaSmaller(BaseStation *st)
01324 {
01325 TileArea ta = st->train_station;
01326
01327 restart:
01328
01329
01330 if (ta.w != 0 && ta.h != 0) {
01331
01332 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(0, i));) {
01333
01334 if (++i == ta.h) {
01335 ta.tile += TileDiffXY(1, 0);
01336 ta.w--;
01337 goto restart;
01338 }
01339 }
01340
01341
01342 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(ta.w - 1, i));) {
01343
01344 if (++i == ta.h) {
01345 ta.w--;
01346 goto restart;
01347 }
01348 }
01349
01350
01351 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(i, 0));) {
01352
01353 if (++i == ta.w) {
01354 ta.tile += TileDiffXY(0, 1);
01355 ta.h--;
01356 goto restart;
01357 }
01358 }
01359
01360
01361 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(i, ta.h - 1));) {
01362
01363 if (++i == ta.w) {
01364 ta.h--;
01365 goto restart;
01366 }
01367 }
01368 } else {
01369 ta.Clear();
01370 }
01371
01372 st->train_station = ta;
01373 }
01374
01385 template <class T>
01386 CommandCost RemoveFromRailBaseStation(TileArea ta, SmallVector<T *, 4> &affected_stations, DoCommandFlag flags, Money removal_cost, bool keep_rail)
01387 {
01388
01389 int quantity = 0;
01390 CommandCost total_cost(EXPENSES_CONSTRUCTION);
01391
01392
01393 TILE_AREA_LOOP(tile, ta) {
01394
01395 if (!HasStationTileRail(tile)) continue;
01396
01397
01398 CommandCost ret = EnsureNoVehicleOnGround(tile);
01399 if (ret.Failed()) continue;
01400
01401
01402 T *st = T::GetByTile(tile);
01403 if (st == NULL) continue;
01404
01405 if (_current_company != OWNER_WATER) {
01406 CommandCost ret = CheckOwnership(st->owner);
01407 if (ret.Failed()) continue;
01408 }
01409
01410
01411 quantity++;
01412
01413 if (keep_rail || IsStationTileBlocked(tile)) {
01414
01415
01416 total_cost.AddCost(-_price[PR_CLEAR_RAIL]);
01417 }
01418
01419 if (flags & DC_EXEC) {
01420
01421 uint specindex = GetCustomStationSpecIndex(tile);
01422 Track track = GetRailStationTrack(tile);
01423 Owner owner = GetTileOwner(tile);
01424 RailType rt = GetRailType(tile);
01425 Train *v = NULL;
01426
01427 if (HasStationReservation(tile)) {
01428 v = GetTrainForReservation(tile, track);
01429 if (v != NULL) {
01430
01431 FreeTrainTrackReservation(v);
01432 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
01433 Vehicle *temp = v;
01434 for (; temp->Next() != NULL; temp = temp->Next()) { }
01435 if (IsRailStationTile(temp->tile)) SetRailStationPlatformReservation(temp->tile, TrackdirToExitdir(ReverseTrackdir(temp->GetVehicleTrackdir())), false);
01436 }
01437 }
01438
01439 bool build_rail = keep_rail && !IsStationTileBlocked(tile);
01440 if (!build_rail && !IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[rt]--;
01441
01442 DoClearSquare(tile);
01443 DeleteNewGRFInspectWindow(GSF_STATIONS, tile);
01444 if (build_rail) MakeRailNormal(tile, owner, TrackToTrackBits(track), rt);
01445 Company::Get(owner)->infrastructure.station--;
01446 DirtyCompanyInfrastructureWindows(owner);
01447
01448 st->rect.AfterRemoveTile(st, tile);
01449 AddTrackToSignalBuffer(tile, track, owner);
01450 YapfNotifyTrackLayoutChange(tile, track);
01451
01452 DeallocateSpecFromStation(st, specindex);
01453
01454 affected_stations.Include(st);
01455
01456 if (v != NULL) {
01457
01458 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
01459 TryPathReserve(v, true, true);
01460 for (; v->Next() != NULL; v = v->Next()) { }
01461 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
01462 }
01463 }
01464 }
01465
01466 if (quantity == 0) return_cmd_error(STR_ERROR_THERE_IS_NO_STATION);
01467
01468 for (T **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
01469 T *st = *stp;
01470
01471
01472
01473
01474 MakeRailStationAreaSmaller(st);
01475 UpdateStationSignCoord(st);
01476
01477
01478 if (st->train_station.tile == INVALID_TILE) {
01479 st->facilities &= ~FACIL_TRAIN;
01480 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
01481 st->UpdateVirtCoord();
01482 DeleteStationIfEmpty(st);
01483 }
01484 }
01485
01486 total_cost.AddCost(quantity * removal_cost);
01487 return total_cost;
01488 }
01489
01501 CommandCost CmdRemoveFromRailStation(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01502 {
01503 TileIndex end = p1 == 0 ? start : p1;
01504 if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
01505
01506 TileArea ta(start, end);
01507 SmallVector<Station *, 4> affected_stations;
01508
01509 CommandCost ret = RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_STATION_RAIL], HasBit(p2, 0));
01510 if (ret.Failed()) return ret;
01511
01512
01513 for (Station **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
01514 Station *st = *stp;
01515
01516 if (st->train_station.tile == INVALID_TILE) SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
01517 st->MarkTilesDirty(false);
01518 st->RecomputeIndustriesNear();
01519 }
01520
01521
01522 return ret;
01523 }
01524
01536 CommandCost CmdRemoveFromRailWaypoint(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01537 {
01538 TileIndex end = p1 == 0 ? start : p1;
01539 if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
01540
01541 TileArea ta(start, end);
01542 SmallVector<Waypoint *, 4> affected_stations;
01543
01544 return RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_WAYPOINT_RAIL], HasBit(p2, 0));
01545 }
01546
01547
01555 template <class T>
01556 CommandCost RemoveRailStation(T *st, DoCommandFlag flags)
01557 {
01558
01559 if (_current_company != OWNER_WATER) {
01560 CommandCost ret = CheckOwnership(st->owner);
01561 if (ret.Failed()) return ret;
01562 }
01563
01564
01565 TileArea ta = st->train_station;
01566
01567 assert(ta.w != 0 && ta.h != 0);
01568
01569 CommandCost cost(EXPENSES_CONSTRUCTION);
01570
01571 TILE_AREA_LOOP(tile, ta) {
01572
01573 if (!st->TileBelongsToRailStation(tile)) continue;
01574
01575 CommandCost ret = EnsureNoVehicleOnGround(tile);
01576 if (ret.Failed()) return ret;
01577
01578 cost.AddCost(_price[PR_CLEAR_STATION_RAIL]);
01579 if (flags & DC_EXEC) {
01580
01581 Track track = GetRailStationTrack(tile);
01582 Owner owner = GetTileOwner(tile);
01583 Train *v = NULL;
01584 if (HasStationReservation(tile)) {
01585 v = GetTrainForReservation(tile, track);
01586 if (v != NULL) FreeTrainTrackReservation(v);
01587 }
01588 if (!IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[GetRailType(tile)]--;
01589 Company::Get(owner)->infrastructure.station--;
01590 DoClearSquare(tile);
01591 DeleteNewGRFInspectWindow(GSF_STATIONS, tile);
01592 AddTrackToSignalBuffer(tile, track, owner);
01593 YapfNotifyTrackLayoutChange(tile, track);
01594 if (v != NULL) TryPathReserve(v, true);
01595 }
01596 }
01597
01598 if (flags & DC_EXEC) {
01599 st->rect.AfterRemoveRect(st, st->train_station);
01600
01601 st->train_station.Clear();
01602
01603 st->facilities &= ~FACIL_TRAIN;
01604
01605 free(st->speclist);
01606 st->num_specs = 0;
01607 st->speclist = NULL;
01608 st->cached_anim_triggers = 0;
01609
01610 DirtyCompanyInfrastructureWindows(st->owner);
01611 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
01612 st->UpdateVirtCoord();
01613 DeleteStationIfEmpty(st);
01614 }
01615
01616 return cost;
01617 }
01618
01625 static CommandCost RemoveRailStation(TileIndex tile, DoCommandFlag flags)
01626 {
01627
01628 if (_current_company == OWNER_WATER) {
01629 return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_STATION);
01630 }
01631
01632 Station *st = Station::GetByTile(tile);
01633 CommandCost cost = RemoveRailStation(st, flags);
01634
01635 if (flags & DC_EXEC) st->RecomputeIndustriesNear();
01636
01637 return cost;
01638 }
01639
01646 static CommandCost RemoveRailWaypoint(TileIndex tile, DoCommandFlag flags)
01647 {
01648
01649 if (_current_company == OWNER_WATER) {
01650 return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_WAYPOINT);
01651 }
01652
01653 return RemoveRailStation(Waypoint::GetByTile(tile), flags);
01654 }
01655
01656
01662 static RoadStop **FindRoadStopSpot(bool truck_station, Station *st)
01663 {
01664 RoadStop **primary_stop = (truck_station) ? &st->truck_stops : &st->bus_stops;
01665
01666 if (*primary_stop == NULL) {
01667
01668 return primary_stop;
01669 } else {
01670
01671 RoadStop *stop = *primary_stop;
01672 while (stop->next != NULL) stop = stop->next;
01673 return &stop->next;
01674 }
01675 }
01676
01677 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags);
01678
01688 static CommandCost FindJoiningRoadStop(StationID existing_stop, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
01689 {
01690 return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST>(existing_stop, station_to_join, adjacent, ta, st);
01691 }
01692
01708 CommandCost CmdBuildRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01709 {
01710 bool type = HasBit(p2, 0);
01711 bool is_drive_through = HasBit(p2, 1);
01712 RoadTypes rts = Extract<RoadTypes, 2, 2>(p2);
01713 StationID station_to_join = GB(p2, 16, 16);
01714 bool reuse = (station_to_join != NEW_STATION);
01715 if (!reuse) station_to_join = INVALID_STATION;
01716 bool distant_join = (station_to_join != INVALID_STATION);
01717
01718 uint8 width = (uint8)GB(p1, 0, 8);
01719 uint8 lenght = (uint8)GB(p1, 8, 8);
01720
01721
01722 if (width > _settings_game.station.station_spread || lenght > _settings_game.station.station_spread) return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
01723
01724 if (width == 0 || lenght == 0) return CMD_ERROR;
01725
01726 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, lenght - 1) == INVALID_TILE) return CMD_ERROR;
01727
01728 TileArea roadstop_area(tile, width, lenght);
01729
01730 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
01731
01732 if (!HasExactlyOneBit(rts) || !HasRoadTypesAvail(_current_company, rts)) return CMD_ERROR;
01733
01734
01735 if (!is_drive_through && HasBit(rts, ROADTYPE_TRAM)) return CMD_ERROR;
01736
01737 DiagDirection ddir = Extract<DiagDirection, 6, 2>(p2);
01738
01739
01740 if (!IsValidDiagDirection(ddir)) return CMD_ERROR;
01741
01742 if (is_drive_through && !IsValidAxis((Axis)ddir)) return CMD_ERROR;
01743
01744 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
01745 if (ret.Failed()) return ret;
01746
01747
01748 CommandCost cost(EXPENSES_CONSTRUCTION, roadstop_area.w * roadstop_area.h * _price[type ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS]);
01749 StationID est = INVALID_STATION;
01750 ret = CheckFlatLandRoadStop(roadstop_area, flags, is_drive_through ? 5 << ddir : 1 << ddir, is_drive_through, type, DiagDirToAxis(ddir), &est, rts);
01751 if (ret.Failed()) return ret;
01752 cost.AddCost(ret);
01753
01754 Station *st = NULL;
01755 ret = FindJoiningRoadStop(est, station_to_join, HasBit(p2, 5), roadstop_area, &st);
01756 if (ret.Failed()) return ret;
01757
01758
01759 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);
01760
01761 ret = BuildStationPart(&st, flags, reuse, roadstop_area, STATIONNAMING_ROAD);
01762 if (ret.Failed()) return ret;
01763
01764 if (flags & DC_EXEC) {
01765
01766 TILE_AREA_LOOP(cur_tile, roadstop_area) {
01767 RoadTypes cur_rts = GetRoadTypes(cur_tile);
01768 Owner road_owner = HasBit(cur_rts, ROADTYPE_ROAD) ? GetRoadOwner(cur_tile, ROADTYPE_ROAD) : _current_company;
01769 Owner tram_owner = HasBit(cur_rts, ROADTYPE_TRAM) ? GetRoadOwner(cur_tile, ROADTYPE_TRAM) : _current_company;
01770
01771 if (IsTileType(cur_tile, MP_STATION) && IsRoadStop(cur_tile)) {
01772 RemoveRoadStop(cur_tile, flags);
01773 }
01774
01775 RoadStop *road_stop = new RoadStop(cur_tile);
01776
01777 RoadStop **currstop = FindRoadStopSpot(type, st);
01778 *currstop = road_stop;
01779
01780 if (type) {
01781 st->truck_station.Add(cur_tile);
01782 } else {
01783 st->bus_station.Add(cur_tile);
01784 }
01785
01786
01787 st->AddFacility((type) ? FACIL_TRUCK_STOP : FACIL_BUS_STOP, cur_tile);
01788
01789 st->rect.BeforeAddTile(cur_tile, StationRect::ADD_TRY);
01790
01791 RoadStopType rs_type = type ? ROADSTOP_TRUCK : ROADSTOP_BUS;
01792 if (is_drive_through) {
01793
01794
01795 RoadType rt;
01796 FOR_EACH_SET_ROADTYPE(rt, cur_rts | rts) {
01797 Company *c = Company::GetIfValid(rt == ROADTYPE_ROAD ? road_owner : tram_owner);
01798 if (c != NULL) {
01799 c->infrastructure.road[rt] += 2 - (IsNormalRoadTile(cur_tile) && HasBit(cur_rts, rt) ? CountBits(GetRoadBits(cur_tile, rt)) : 0);
01800 DirtyCompanyInfrastructureWindows(c->index);
01801 }
01802 }
01803
01804 MakeDriveThroughRoadStop(cur_tile, st->owner, road_owner, tram_owner, st->index, rs_type, rts | cur_rts, DiagDirToAxis(ddir));
01805 road_stop->MakeDriveThrough();
01806 } else {
01807
01808 Company::Get(st->owner)->infrastructure.road[FIND_FIRST_BIT(rts)] += 2;
01809 MakeRoadStop(cur_tile, st->owner, st->index, rs_type, rts, ddir);
01810 }
01811 Company::Get(st->owner)->infrastructure.station++;
01812 DirtyCompanyInfrastructureWindows(st->owner);
01813
01814 MarkTileDirtyByTile(cur_tile);
01815 }
01816 }
01817
01818 if (st != NULL) {
01819 st->UpdateVirtCoord();
01820 UpdateStationAcceptance(st, false);
01821 st->RecomputeIndustriesNear();
01822 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
01823 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
01824 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ROADVEHS);
01825 }
01826 return cost;
01827 }
01828
01829
01830 static Vehicle *ClearRoadStopStatusEnum(Vehicle *v, void *)
01831 {
01832 if (v->type == VEH_ROAD) {
01833
01834
01835
01836
01837
01838
01839 RoadVehicle *rv = RoadVehicle::From(v);
01840 if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) rv->state &= RVSB_ROAD_STOP_TRACKDIR_MASK;
01841 }
01842
01843 return NULL;
01844 }
01845
01846
01853 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags)
01854 {
01855 Station *st = Station::GetByTile(tile);
01856
01857 if (_current_company != OWNER_WATER) {
01858 CommandCost ret = CheckOwnership(st->owner);
01859 if (ret.Failed()) return ret;
01860 }
01861
01862 bool is_truck = IsTruckStop(tile);
01863
01864 RoadStop **primary_stop;
01865 RoadStop *cur_stop;
01866 if (is_truck) {
01867 primary_stop = &st->truck_stops;
01868 cur_stop = RoadStop::GetByTile(tile, ROADSTOP_TRUCK);
01869 } else {
01870 primary_stop = &st->bus_stops;
01871 cur_stop = RoadStop::GetByTile(tile, ROADSTOP_BUS);
01872 }
01873
01874 assert(cur_stop != NULL);
01875
01876
01877 if (IsDriveThroughStopTile(tile) && (flags & DC_BANKRUPT)) {
01878
01879 if (flags & DC_EXEC) FindVehicleOnPos(tile, NULL, &ClearRoadStopStatusEnum);
01880 } else {
01881 CommandCost ret = EnsureNoVehicleOnGround(tile);
01882 if (ret.Failed()) return ret;
01883 }
01884
01885 if (flags & DC_EXEC) {
01886 if (*primary_stop == cur_stop) {
01887
01888 *primary_stop = cur_stop->next;
01889
01890 if (*primary_stop == NULL) {
01891 st->facilities &= (is_truck ? ~FACIL_TRUCK_STOP : ~FACIL_BUS_STOP);
01892 }
01893 } else {
01894
01895 RoadStop *pred = *primary_stop;
01896 while (pred->next != cur_stop) pred = pred->next;
01897 pred->next = cur_stop->next;
01898 }
01899
01900
01901 RoadType rt;
01902 FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(tile)) {
01903 Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
01904 if (c != NULL) {
01905 c->infrastructure.road[rt] -= 2;
01906 DirtyCompanyInfrastructureWindows(c->index);
01907 }
01908 }
01909 Company::Get(st->owner)->infrastructure.station--;
01910
01911 if (IsDriveThroughStopTile(tile)) {
01912
01913 cur_stop->ClearDriveThrough();
01914 } else {
01915 DoClearSquare(tile);
01916 }
01917
01918 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ROADVEHS);
01919 delete cur_stop;
01920
01921
01922 RoadVehicle *v;
01923 FOR_ALL_ROADVEHICLES(v) {
01924 if (v->First() == v && v->current_order.IsType(OT_GOTO_STATION) &&
01925 v->dest_tile == tile) {
01926 v->dest_tile = v->GetOrderStationLocation(st->index);
01927 }
01928 }
01929
01930 st->rect.AfterRemoveTile(st, tile);
01931
01932 st->UpdateVirtCoord();
01933 st->RecomputeIndustriesNear();
01934 DeleteStationIfEmpty(st);
01935
01936
01937 if (is_truck) {
01938 st->truck_station.Clear();
01939 for (const RoadStop *rs = st->truck_stops; rs != NULL; rs = rs->next) st->truck_station.Add(rs->xy);
01940 } else {
01941 st->bus_station.Clear();
01942 for (const RoadStop *rs = st->bus_stops; rs != NULL; rs = rs->next) st->bus_station.Add(rs->xy);
01943 }
01944 }
01945
01946 return CommandCost(EXPENSES_CONSTRUCTION, _price[is_truck ? PR_CLEAR_STATION_TRUCK : PR_CLEAR_STATION_BUS]);
01947 }
01948
01959 CommandCost CmdRemoveRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01960 {
01961 uint8 width = (uint8)GB(p1, 0, 8);
01962 uint8 height = (uint8)GB(p1, 8, 8);
01963
01964
01965 if (width == 0 || height == 0) return CMD_ERROR;
01966
01967 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, height - 1) == INVALID_TILE) return CMD_ERROR;
01968
01969 TileArea roadstop_area(tile, width, height);
01970
01971 int quantity = 0;
01972 CommandCost cost(EXPENSES_CONSTRUCTION);
01973 TILE_AREA_LOOP(cur_tile, roadstop_area) {
01974
01975 if (!IsTileType(cur_tile, MP_STATION) || !IsRoadStop(cur_tile) || (uint32)GetRoadStopType(cur_tile) != GB(p2, 0, 1)) continue;
01976
01977
01978 bool is_drive_through = IsDriveThroughStopTile(cur_tile);
01979 RoadTypes rts = GetRoadTypes(cur_tile);
01980 RoadBits road_bits = IsDriveThroughStopTile(cur_tile) ?
01981 ((GetRoadStopDir(cur_tile) == DIAGDIR_NE) ? ROAD_X : ROAD_Y) :
01982 DiagDirToRoadBits(GetRoadStopDir(cur_tile));
01983
01984 Owner road_owner = GetRoadOwner(cur_tile, ROADTYPE_ROAD);
01985 Owner tram_owner = GetRoadOwner(cur_tile, ROADTYPE_TRAM);
01986 CommandCost ret = RemoveRoadStop(cur_tile, flags);
01987 if (ret.Failed()) return ret;
01988 cost.AddCost(ret);
01989
01990 quantity++;
01991
01992 if ((flags & DC_EXEC) && is_drive_through) {
01993 MakeRoadNormal(cur_tile, road_bits, rts, ClosestTownFromTile(cur_tile, UINT_MAX)->index,
01994 road_owner, tram_owner);
01995
01996
01997 RoadType rt;
01998 FOR_EACH_SET_ROADTYPE(rt, rts) {
01999 Company *c = Company::GetIfValid(GetRoadOwner(cur_tile, rt));
02000 if (c != NULL) {
02001 c->infrastructure.road[rt] += CountBits(road_bits);
02002 DirtyCompanyInfrastructureWindows(c->index);
02003 }
02004 }
02005 }
02006 }
02007
02008 if (quantity == 0) return_cmd_error(STR_ERROR_THERE_IS_NO_STATION);
02009
02010 return cost;
02011 }
02012
02019 static uint GetMinimalAirportDistanceToTile(TileIterator &it, TileIndex town_tile)
02020 {
02021 uint mindist = UINT_MAX;
02022
02023 for (TileIndex cur_tile = it; cur_tile != INVALID_TILE; cur_tile = ++it) {
02024 mindist = min(mindist, DistanceManhattan(town_tile, cur_tile));
02025 }
02026
02027 return mindist;
02028 }
02029
02039 uint8 GetAirportNoiseLevelForTown(const AirportSpec *as, TileIterator &it, TileIndex town_tile)
02040 {
02041
02042
02043 if (as->noise_level < 2) return as->noise_level;
02044
02045 uint distance = GetMinimalAirportDistanceToTile(it, town_tile);
02046
02047
02048
02049
02050
02051 uint8 town_tolerance_distance = 8 + (_settings_game.difficulty.town_council_tolerance * 4);
02052
02053
02054
02055 uint noise_reduction = distance / town_tolerance_distance;
02056
02057
02058
02059 return noise_reduction >= as->noise_level ? 1 : as->noise_level - noise_reduction;
02060 }
02061
02069 Town *AirportGetNearestTown(const AirportSpec *as, const TileIterator &it)
02070 {
02071 Town *t, *nearest = NULL;
02072 uint add = as->size_x + as->size_y - 2;
02073 uint mindist = UINT_MAX - add;
02074 FOR_ALL_TOWNS(t) {
02075 if (DistanceManhattan(t->xy, it) < mindist + add) {
02076 TileIterator *copy = it.Clone();
02077 uint dist = GetMinimalAirportDistanceToTile(*copy, t->xy);
02078 delete copy;
02079 if (dist < mindist) {
02080 nearest = t;
02081 mindist = dist;
02082 }
02083 }
02084 }
02085
02086 return nearest;
02087 }
02088
02089
02091 void UpdateAirportsNoise()
02092 {
02093 Town *t;
02094 const Station *st;
02095
02096 FOR_ALL_TOWNS(t) t->noise_reached = 0;
02097
02098 FOR_ALL_STATIONS(st) {
02099 if (st->airport.tile != INVALID_TILE && st->airport.type != AT_OILRIG) {
02100 const AirportSpec *as = st->airport.GetSpec();
02101 AirportTileIterator it(st);
02102 Town *nearest = AirportGetNearestTown(as, it);
02103 nearest->noise_reached += GetAirportNoiseLevelForTown(as, it, nearest->xy);
02104 }
02105 }
02106 }
02107
02121 CommandCost CmdBuildAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02122 {
02123 StationID station_to_join = GB(p2, 16, 16);
02124 bool reuse = (station_to_join != NEW_STATION);
02125 if (!reuse) station_to_join = INVALID_STATION;
02126 bool distant_join = (station_to_join != INVALID_STATION);
02127 byte airport_type = GB(p1, 0, 8);
02128 byte layout = GB(p1, 8, 8);
02129
02130 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
02131
02132 if (airport_type >= NUM_AIRPORTS) return CMD_ERROR;
02133
02134 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
02135 if (ret.Failed()) return ret;
02136
02137
02138 const AirportSpec *as = AirportSpec::Get(airport_type);
02139 if (!as->IsAvailable() || layout >= as->num_table) return CMD_ERROR;
02140
02141 Direction rotation = as->rotation[layout];
02142 int w = as->size_x;
02143 int h = as->size_y;
02144 if (rotation == DIR_E || rotation == DIR_W) Swap(w, h);
02145 TileArea airport_area = TileArea(tile, w, h);
02146
02147 if (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread) {
02148 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
02149 }
02150
02151 CommandCost cost = CheckFlatLand(airport_area, flags);
02152 if (cost.Failed()) return cost;
02153
02154
02155 AirportTileTableIterator iter(as->table[layout], tile);
02156 Town *nearest = AirportGetNearestTown(as, iter);
02157 uint newnoise_level = GetAirportNoiseLevelForTown(as, iter, nearest->xy);
02158
02159
02160 StringID authority_refuse_message = STR_NULL;
02161 Town *authority_refuse_town = NULL;
02162
02163 if (_settings_game.economy.station_noise_level) {
02164
02165 if ((nearest->noise_reached + newnoise_level) > nearest->MaxTownNoise()) {
02166 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE;
02167 authority_refuse_town = nearest;
02168 }
02169 } else {
02170 Town *t = ClosestTownFromTile(tile, UINT_MAX);
02171 uint num = 0;
02172 const Station *st;
02173 FOR_ALL_STATIONS(st) {
02174 if (st->town == t && (st->facilities & FACIL_AIRPORT) && st->airport.type != AT_OILRIG) num++;
02175 }
02176 if (num >= 2) {
02177 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT;
02178 authority_refuse_town = t;
02179 }
02180 }
02181
02182 if (authority_refuse_message != STR_NULL) {
02183 SetDParam(0, authority_refuse_town->index);
02184 return_cmd_error(authority_refuse_message);
02185 }
02186
02187 Station *st = NULL;
02188 ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p2, 0), airport_area, &st);
02189 if (ret.Failed()) return ret;
02190
02191
02192 if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
02193
02194 ret = BuildStationPart(&st, flags, reuse, airport_area, (GetAirport(airport_type)->flags & AirportFTAClass::AIRPLANES) ? STATIONNAMING_AIRPORT : STATIONNAMING_HELIPORT);
02195 if (ret.Failed()) return ret;
02196
02197 if (st != NULL && st->airport.tile != INVALID_TILE) {
02198 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT);
02199 }
02200
02201 for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
02202 cost.AddCost(_price[PR_BUILD_STATION_AIRPORT]);
02203 }
02204
02205 if (flags & DC_EXEC) {
02206
02207 nearest->noise_reached += newnoise_level;
02208
02209 st->AddFacility(FACIL_AIRPORT, tile);
02210 st->airport.type = airport_type;
02211 st->airport.layout = layout;
02212 st->airport.flags = 0;
02213 st->airport.rotation = rotation;
02214
02215 st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TRY);
02216
02217 for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
02218 MakeAirport(iter, st->owner, st->index, iter.GetStationGfx(), WATER_CLASS_INVALID);
02219 SetStationTileRandomBits(iter, GB(Random(), 0, 4));
02220 st->airport.Add(iter);
02221
02222 if (AirportTileSpec::Get(GetTranslatedAirportTileID(iter.GetStationGfx()))->animation.status != ANIM_STATUS_NO_ANIMATION) AddAnimatedTile(iter);
02223 }
02224
02225
02226 for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
02227 AirportTileAnimationTrigger(st, iter, AAT_BUILT);
02228 }
02229
02230 UpdateAirplanesOnNewStation(st);
02231
02232 Company::Get(st->owner)->infrastructure.airport++;
02233 DirtyCompanyInfrastructureWindows(st->owner);
02234
02235 st->UpdateVirtCoord();
02236 UpdateStationAcceptance(st, false);
02237 st->RecomputeIndustriesNear();
02238 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
02239 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
02240 InvalidateWindowData(WC_STATION_VIEW, st->index, -1);
02241
02242 if (_settings_game.economy.station_noise_level) {
02243 SetWindowDirty(WC_TOWN_VIEW, st->town->index);
02244 }
02245 }
02246
02247 return cost;
02248 }
02249
02256 static CommandCost RemoveAirport(TileIndex tile, DoCommandFlag flags)
02257 {
02258 Station *st = Station::GetByTile(tile);
02259
02260 if (_current_company != OWNER_WATER) {
02261 CommandCost ret = CheckOwnership(st->owner);
02262 if (ret.Failed()) return ret;
02263 }
02264
02265 tile = st->airport.tile;
02266
02267 CommandCost cost(EXPENSES_CONSTRUCTION);
02268
02269 const Aircraft *a;
02270 FOR_ALL_AIRCRAFT(a) {
02271 if (!a->IsNormalAircraft()) continue;
02272 if (a->targetairport == st->index && a->state != FLYING) return CMD_ERROR;
02273 }
02274
02275 if (flags & DC_EXEC) {
02276 const AirportSpec *as = st->airport.GetSpec();
02277
02278
02279
02280 AirportTileIterator it(st);
02281 Town *nearest = AirportGetNearestTown(as, it);
02282 nearest->noise_reached -= GetAirportNoiseLevelForTown(as, it, nearest->xy);
02283 }
02284
02285 TILE_AREA_LOOP(tile_cur, st->airport) {
02286 if (!st->TileBelongsToAirport(tile_cur)) continue;
02287
02288 CommandCost ret = EnsureNoVehicleOnGround(tile_cur);
02289 if (ret.Failed()) return ret;
02290
02291 cost.AddCost(_price[PR_CLEAR_STATION_AIRPORT]);
02292
02293 if (flags & DC_EXEC) {
02294 if (IsHangarTile(tile_cur)) OrderBackup::Reset(tile_cur, false);
02295 DeleteAnimatedTile(tile_cur);
02296 DoClearSquare(tile_cur);
02297 DeleteNewGRFInspectWindow(GSF_AIRPORTTILES, tile_cur);
02298 }
02299 }
02300
02301 if (flags & DC_EXEC) {
02302
02303 delete st->airport.psa;
02304
02305 for (uint i = 0; i < st->airport.GetNumHangars(); ++i) {
02306 DeleteWindowById(
02307 WC_VEHICLE_DEPOT, st->airport.GetHangarTile(i)
02308 );
02309 }
02310
02311 st->rect.AfterRemoveRect(st, st->airport);
02312
02313 st->airport.Clear();
02314 st->facilities &= ~FACIL_AIRPORT;
02315
02316 InvalidateWindowData(WC_STATION_VIEW, st->index, -1);
02317
02318 if (_settings_game.economy.station_noise_level) {
02319 SetWindowDirty(WC_TOWN_VIEW, st->town->index);
02320 }
02321
02322 Company::Get(st->owner)->infrastructure.airport--;
02323 DirtyCompanyInfrastructureWindows(st->owner);
02324
02325 st->UpdateVirtCoord();
02326 st->RecomputeIndustriesNear();
02327 DeleteStationIfEmpty(st);
02328 DeleteNewGRFInspectWindow(GSF_AIRPORTS, st->index);
02329 }
02330
02331 return cost;
02332 }
02333
02343 CommandCost CmdOpenCloseAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02344 {
02345 if (!Station::IsValidID(p1)) return CMD_ERROR;
02346 Station *st = Station::Get(p1);
02347
02348 if (!(st->facilities & FACIL_AIRPORT) || st->owner == OWNER_NONE) return CMD_ERROR;
02349
02350 CommandCost ret = CheckOwnership(st->owner);
02351 if (ret.Failed()) return ret;
02352
02353 if (flags & DC_EXEC) {
02354 st->airport.flags ^= AIRPORT_CLOSED_block;
02355 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_CLOSE_AIRPORT);
02356 }
02357 return CommandCost();
02358 }
02359
02366 bool HasStationInUse(StationID station, bool include_company, CompanyID company)
02367 {
02368 const Vehicle *v;
02369 FOR_ALL_VEHICLES(v) {
02370 if ((v->owner == company) == include_company) {
02371 const Order *order;
02372 FOR_VEHICLE_ORDERS(v, order) {
02373 if ((order->IsType(OT_GOTO_STATION) || order->IsType(OT_GOTO_WAYPOINT)) && order->GetDestination() == station) {
02374 return true;
02375 }
02376 }
02377 }
02378 }
02379 return false;
02380 }
02381
02382 static const TileIndexDiffC _dock_tileoffs_chkaround[] = {
02383 {-1, 0},
02384 { 0, 0},
02385 { 0, 0},
02386 { 0, -1}
02387 };
02388 static const byte _dock_w_chk[4] = { 2, 1, 2, 1 };
02389 static const byte _dock_h_chk[4] = { 1, 2, 1, 2 };
02390
02400 CommandCost CmdBuildDock(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02401 {
02402 StationID station_to_join = GB(p2, 16, 16);
02403 bool reuse = (station_to_join != NEW_STATION);
02404 if (!reuse) station_to_join = INVALID_STATION;
02405 bool distant_join = (station_to_join != INVALID_STATION);
02406
02407 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
02408
02409 DiagDirection direction = GetInclinedSlopeDirection(GetTileSlope(tile));
02410 if (direction == INVALID_DIAGDIR) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02411 direction = ReverseDiagDir(direction);
02412
02413
02414 if (HasTileWaterGround(tile)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02415
02416 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
02417 if (ret.Failed()) return ret;
02418
02419 if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
02420
02421 ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02422 if (ret.Failed()) return ret;
02423
02424 TileIndex tile_cur = tile + TileOffsByDiagDir(direction);
02425
02426 if (!IsTileType(tile_cur, MP_WATER) || GetTileSlope(tile_cur) != SLOPE_FLAT) {
02427 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02428 }
02429
02430 if (MayHaveBridgeAbove(tile_cur) && IsBridgeAbove(tile_cur)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
02431
02432
02433 WaterClass wc = GetWaterClass(tile_cur);
02434
02435 ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02436 if (ret.Failed()) return ret;
02437
02438 tile_cur += TileOffsByDiagDir(direction);
02439 if (!IsTileType(tile_cur, MP_WATER) || GetTileSlope(tile_cur) != SLOPE_FLAT) {
02440 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02441 }
02442
02443 TileArea dock_area = TileArea(tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
02444 _dock_w_chk[direction], _dock_h_chk[direction]);
02445
02446
02447 Station *st = NULL;
02448 ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p1, 0), dock_area, &st);
02449 if (ret.Failed()) return ret;
02450
02451
02452 if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
02453
02454 ret = BuildStationPart(&st, flags, reuse, dock_area, STATIONNAMING_DOCK);
02455 if (ret.Failed()) return ret;
02456
02457 if (st != NULL && st->dock_tile != INVALID_TILE) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_DOCK);
02458
02459 if (flags & DC_EXEC) {
02460 st->dock_tile = tile;
02461 st->AddFacility(FACIL_DOCK, tile);
02462
02463 st->rect.BeforeAddRect(dock_area.tile, dock_area.w, dock_area.h, StationRect::ADD_TRY);
02464
02465
02466
02467 if (wc == WATER_CLASS_CANAL) {
02468 Company::Get(st->owner)->infrastructure.water++;
02469 }
02470 Company::Get(st->owner)->infrastructure.station += 2;
02471 DirtyCompanyInfrastructureWindows(st->owner);
02472
02473 MakeDock(tile, st->owner, st->index, direction, wc);
02474
02475 st->UpdateVirtCoord();
02476 UpdateStationAcceptance(st, false);
02477 st->RecomputeIndustriesNear();
02478 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
02479 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
02480 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_SHIPS);
02481 }
02482
02483 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_STATION_DOCK]);
02484 }
02485
02492 static CommandCost RemoveDock(TileIndex tile, DoCommandFlag flags)
02493 {
02494 Station *st = Station::GetByTile(tile);
02495 CommandCost ret = CheckOwnership(st->owner);
02496 if (ret.Failed()) return ret;
02497
02498 TileIndex docking_location = TILE_ADD(st->dock_tile, ToTileIndexDiff(GetDockOffset(st->dock_tile)));
02499
02500 TileIndex tile1 = st->dock_tile;
02501 TileIndex tile2 = tile1 + TileOffsByDiagDir(GetDockDirection(tile1));
02502
02503 ret = EnsureNoVehicleOnGround(tile1);
02504 if (ret.Succeeded()) ret = EnsureNoVehicleOnGround(tile2);
02505 if (ret.Failed()) return ret;
02506
02507 if (flags & DC_EXEC) {
02508 DoClearSquare(tile1);
02509 MarkTileDirtyByTile(tile1);
02510 MakeWaterKeepingClass(tile2, st->owner);
02511
02512 st->rect.AfterRemoveTile(st, tile1);
02513 st->rect.AfterRemoveTile(st, tile2);
02514
02515 st->dock_tile = INVALID_TILE;
02516 st->facilities &= ~FACIL_DOCK;
02517
02518 Company::Get(st->owner)->infrastructure.station -= 2;
02519 DirtyCompanyInfrastructureWindows(st->owner);
02520
02521 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_SHIPS);
02522 st->UpdateVirtCoord();
02523 st->RecomputeIndustriesNear();
02524 DeleteStationIfEmpty(st);
02525
02526
02527
02528
02529
02530 Ship *s;
02531 FOR_ALL_SHIPS(s) {
02532 if (s->current_order.IsType(OT_LOADING) && s->tile == docking_location) {
02533 s->LeaveStation();
02534 }
02535
02536 if (s->dest_tile == docking_location) {
02537 s->dest_tile = 0;
02538 s->current_order.Free();
02539 }
02540 }
02541 }
02542
02543 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_STATION_DOCK]);
02544 }
02545
02546 #include "table/station_land.h"
02547
02548 const DrawTileSprites *GetStationTileLayout(StationType st, byte gfx)
02549 {
02550 return &_station_display_datas[st][gfx];
02551 }
02552
02562 bool SplitGroundSpriteForOverlay(const TileInfo *ti, SpriteID *ground, RailTrackOffset *overlay_offset)
02563 {
02564 bool snow_desert;
02565 switch (*ground) {
02566 case SPR_RAIL_TRACK_X:
02567 snow_desert = false;
02568 *overlay_offset = RTO_X;
02569 break;
02570
02571 case SPR_RAIL_TRACK_Y:
02572 snow_desert = false;
02573 *overlay_offset = RTO_Y;
02574 break;
02575
02576 case SPR_RAIL_TRACK_X_SNOW:
02577 snow_desert = true;
02578 *overlay_offset = RTO_X;
02579 break;
02580
02581 case SPR_RAIL_TRACK_Y_SNOW:
02582 snow_desert = true;
02583 *overlay_offset = RTO_Y;
02584 break;
02585
02586 default:
02587 return false;
02588 }
02589
02590 if (ti != NULL) {
02591
02592 switch (_settings_game.game_creation.landscape) {
02593 case LT_ARCTIC:
02594 snow_desert = (uint)ti->z > GetSnowLine() * TILE_HEIGHT;
02595 break;
02596
02597 case LT_TROPIC:
02598 snow_desert = GetTropicZone(ti->tile) == TROPICZONE_DESERT;
02599 break;
02600
02601 default:
02602 break;
02603 }
02604 }
02605
02606 *ground = snow_desert ? SPR_FLAT_SNOW_DESERT_TILE : SPR_FLAT_GRASS_TILE;
02607 return true;
02608 }
02609
02610 static void DrawTile_Station(TileInfo *ti)
02611 {
02612 const NewGRFSpriteLayout *layout = NULL;
02613 DrawTileSprites tmp_rail_layout;
02614 const DrawTileSprites *t = NULL;
02615 RoadTypes roadtypes;
02616 int32 total_offset;
02617 const RailtypeInfo *rti = NULL;
02618 uint32 relocation = 0;
02619 uint32 ground_relocation = 0;
02620 BaseStation *st = NULL;
02621 const StationSpec *statspec = NULL;
02622 uint tile_layout = 0;
02623
02624 if (HasStationRail(ti->tile)) {
02625 rti = GetRailTypeInfo(GetRailType(ti->tile));
02626 roadtypes = ROADTYPES_NONE;
02627 total_offset = rti->GetRailtypeSpriteOffset();
02628
02629 if (IsCustomStationSpecIndex(ti->tile)) {
02630
02631 st = BaseStation::GetByTile(ti->tile);
02632 statspec = st->speclist[GetCustomStationSpecIndex(ti->tile)].spec;
02633
02634 if (statspec != NULL) {
02635 tile_layout = GetStationGfx(ti->tile);
02636
02637 if (HasBit(statspec->callback_mask, CBM_STATION_SPRITE_LAYOUT)) {
02638 uint16 callback = GetStationCallback(CBID_STATION_SPRITE_LAYOUT, 0, 0, statspec, st, ti->tile);
02639 if (callback != CALLBACK_FAILED) tile_layout = (callback & ~1) + GetRailStationAxis(ti->tile);
02640 }
02641
02642
02643 if (statspec->renderdata != NULL) {
02644 layout = &statspec->renderdata[tile_layout < statspec->tiles ? tile_layout : (uint)GetRailStationAxis(ti->tile)];
02645 if (!layout->NeedsPreprocessing()) {
02646 t = layout;
02647 layout = NULL;
02648 }
02649 }
02650 }
02651 }
02652 } else {
02653 roadtypes = IsRoadStop(ti->tile) ? GetRoadTypes(ti->tile) : ROADTYPES_NONE;
02654 total_offset = 0;
02655 }
02656
02657 StationGfx gfx = GetStationGfx(ti->tile);
02658 if (IsAirport(ti->tile)) {
02659 gfx = GetAirportGfx(ti->tile);
02660 if (gfx >= NEW_AIRPORTTILE_OFFSET) {
02661 const AirportTileSpec *ats = AirportTileSpec::Get(gfx);
02662 if (ats->grf_prop.spritegroup[0] != NULL && DrawNewAirportTile(ti, Station::GetByTile(ti->tile), gfx, ats)) {
02663 return;
02664 }
02665
02666
02667 assert(ats->grf_prop.subst_id != INVALID_AIRPORTTILE);
02668 gfx = ats->grf_prop.subst_id;
02669 }
02670 switch (gfx) {
02671 case APT_RADAR_GRASS_FENCE_SW:
02672 t = &_station_display_datas_airport_radar_grass_fence_sw[GetAnimationFrame(ti->tile)];
02673 break;
02674 case APT_GRASS_FENCE_NE_FLAG:
02675 t = &_station_display_datas_airport_flag_grass_fence_ne[GetAnimationFrame(ti->tile)];
02676 break;
02677 case APT_RADAR_FENCE_SW:
02678 t = &_station_display_datas_airport_radar_fence_sw[GetAnimationFrame(ti->tile)];
02679 break;
02680 case APT_RADAR_FENCE_NE:
02681 t = &_station_display_datas_airport_radar_fence_ne[GetAnimationFrame(ti->tile)];
02682 break;
02683 case APT_GRASS_FENCE_NE_FLAG_2:
02684 t = &_station_display_datas_airport_flag_grass_fence_ne_2[GetAnimationFrame(ti->tile)];
02685 break;
02686 }
02687 }
02688
02689 Owner owner = GetTileOwner(ti->tile);
02690
02691 PaletteID palette;
02692 if (Company::IsValidID(owner)) {
02693 palette = COMPANY_SPRITE_COLOUR(owner);
02694 } else {
02695
02696 palette = PALETTE_TO_GREY;
02697 }
02698
02699 if (layout == NULL && (t == NULL || t->seq == NULL)) t = GetStationTileLayout(GetStationType(ti->tile), gfx);
02700
02701
02702 if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile)) {
02703 if (statspec != NULL && HasBit(statspec->flags, SSF_CUSTOM_FOUNDATIONS)) {
02704
02705
02706 uint edge_info = 0;
02707 int z;
02708 Slope slope = GetFoundationPixelSlope(ti->tile, &z);
02709 if (!HasFoundationNW(ti->tile, slope, z)) SetBit(edge_info, 0);
02710 if (!HasFoundationNE(ti->tile, slope, z)) SetBit(edge_info, 1);
02711 SpriteID image = GetCustomStationFoundationRelocation(statspec, st, ti->tile, tile_layout, edge_info);
02712 if (image == 0) goto draw_default_foundation;
02713
02714 if (HasBit(statspec->flags, SSF_EXTENDED_FOUNDATIONS)) {
02715
02716
02717 static const uint8 foundation_parts[] = {
02718 0, 0, 0, 0,
02719 0, 1, 2, 3,
02720 0, 4, 5, 6,
02721 7, 8, 9
02722 };
02723
02724 AddSortableSpriteToDraw(image + foundation_parts[ti->tileh], PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
02725 } else {
02726
02727
02728
02729
02730 static const uint8 composite_foundation_parts[] = {
02731
02732 0x00, 0xD1, 0xE4, 0xE0,
02733
02734 0xCA, 0xC9, 0xC4, 0xC0,
02735
02736 0xD2, 0x91, 0xE4, 0xA0,
02737
02738 0x4A, 0x09, 0x44
02739 };
02740
02741 uint8 parts = composite_foundation_parts[ti->tileh];
02742
02743
02744
02745 if (HasBit(edge_info, 0)) ClrBit(parts, 6);
02746 if (HasBit(edge_info, 1)) ClrBit(parts, 7);
02747
02748 if (parts == 0) {
02749
02750
02751
02752 goto draw_default_foundation;
02753 }
02754
02755 StartSpriteCombine();
02756 for (int i = 0; i < 8; i++) {
02757 if (HasBit(parts, i)) {
02758 AddSortableSpriteToDraw(image + i, PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
02759 }
02760 }
02761 EndSpriteCombine();
02762 }
02763
02764 OffsetGroundSprite(31, 1);
02765 ti->z += ApplyPixelFoundationToSlope(FOUNDATION_LEVELED, &ti->tileh);
02766 } else {
02767 draw_default_foundation:
02768 DrawFoundation(ti, FOUNDATION_LEVELED);
02769 }
02770 }
02771
02772 if (IsBuoy(ti->tile)) {
02773 DrawWaterClassGround(ti);
02774 SpriteID sprite = GetCanalSprite(CF_BUOY, ti->tile);
02775 if (sprite != 0) total_offset = sprite - SPR_IMG_BUOY;
02776 } else if (IsDock(ti->tile) || (IsOilRig(ti->tile) && IsTileOnWater(ti->tile))) {
02777 if (ti->tileh == SLOPE_FLAT) {
02778 DrawWaterClassGround(ti);
02779 } else {
02780 assert(IsDock(ti->tile));
02781 TileIndex water_tile = ti->tile + TileOffsByDiagDir(GetDockDirection(ti->tile));
02782 WaterClass wc = GetWaterClass(water_tile);
02783 if (wc == WATER_CLASS_SEA) {
02784 DrawShoreTile(ti->tileh);
02785 } else {
02786 DrawClearLandTile(ti, 3);
02787 }
02788 }
02789 } else {
02790 if (layout != NULL) {
02791
02792 bool separate_ground = HasBit(statspec->flags, SSF_SEPARATE_GROUND);
02793 uint32 var10_values = layout->PrepareLayout(total_offset, rti->fallback_railtype, 0, 0, separate_ground);
02794 uint8 var10;
02795 FOR_EACH_SET_BIT(var10, var10_values) {
02796 uint32 var10_relocation = GetCustomStationRelocation(statspec, st, ti->tile, var10);
02797 layout->ProcessRegisters(var10, var10_relocation, separate_ground);
02798 }
02799 tmp_rail_layout.seq = layout->GetLayout(&tmp_rail_layout.ground);
02800 t = &tmp_rail_layout;
02801 total_offset = 0;
02802 } else if (statspec != NULL) {
02803
02804 ground_relocation = relocation = GetCustomStationRelocation(statspec, st, ti->tile, 0);
02805 if (HasBit(statspec->flags, SSF_SEPARATE_GROUND)) {
02806 ground_relocation = GetCustomStationRelocation(statspec, st, ti->tile, 1);
02807 }
02808 ground_relocation += rti->fallback_railtype;
02809 }
02810
02811 SpriteID image = t->ground.sprite;
02812 PaletteID pal = t->ground.pal;
02813 RailTrackOffset overlay_offset;
02814 if (rti != NULL && rti->UsesOverlay() && SplitGroundSpriteForOverlay(ti, &image, &overlay_offset)) {
02815 SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
02816 DrawGroundSprite(image, PAL_NONE);
02817 DrawGroundSprite(ground + overlay_offset, PAL_NONE);
02818
02819 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationReservation(ti->tile)) {
02820 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
02821 DrawGroundSprite(overlay + overlay_offset, PALETTE_CRASH);
02822 }
02823 } else {
02824 image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
02825 if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
02826 DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
02827
02828
02829 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationRail(ti->tile) && HasStationReservation(ti->tile)) {
02830 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
02831 DrawGroundSprite(GetRailStationAxis(ti->tile) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH);
02832 }
02833 }
02834 }
02835
02836 if (HasStationRail(ti->tile) && HasCatenaryDrawn(GetRailType(ti->tile))) DrawCatenary(ti);
02837
02838 if (HasBit(roadtypes, ROADTYPE_TRAM)) {
02839 Axis axis = GetRoadStopDir(ti->tile) == DIAGDIR_NE ? AXIS_X : AXIS_Y;
02840 DrawGroundSprite((HasBit(roadtypes, ROADTYPE_ROAD) ? SPR_TRAMWAY_OVERLAY : SPR_TRAMWAY_TRAM) + (axis ^ 1), PAL_NONE);
02841 DrawTramCatenary(ti, axis == AXIS_X ? ROAD_X : ROAD_Y);
02842 }
02843
02844 if (IsRailWaypoint(ti->tile)) {
02845
02846 total_offset = 0;
02847 }
02848
02849 DrawRailTileSeq(ti, t, TO_BUILDINGS, total_offset, relocation, palette);
02850 }
02851
02852 void StationPickerDrawSprite(int x, int y, StationType st, RailType railtype, RoadType roadtype, int image)
02853 {
02854 int32 total_offset = 0;
02855 PaletteID pal = COMPANY_SPRITE_COLOUR(_local_company);
02856 const DrawTileSprites *t = GetStationTileLayout(st, image);
02857 const RailtypeInfo *rti = NULL;
02858
02859 if (railtype != INVALID_RAILTYPE) {
02860 rti = GetRailTypeInfo(railtype);
02861 total_offset = rti->GetRailtypeSpriteOffset();
02862 }
02863
02864 SpriteID img = t->ground.sprite;
02865 RailTrackOffset overlay_offset;
02866 if (rti != NULL && rti->UsesOverlay() && SplitGroundSpriteForOverlay(NULL, &img, &overlay_offset)) {
02867 SpriteID ground = GetCustomRailSprite(rti, INVALID_TILE, RTSG_GROUND);
02868 DrawSprite(img, PAL_NONE, x, y);
02869 DrawSprite(ground + overlay_offset, PAL_NONE, x, y);
02870 } else {
02871 DrawSprite(img + total_offset, HasBit(img, PALETTE_MODIFIER_COLOUR) ? pal : PAL_NONE, x, y);
02872 }
02873
02874 if (roadtype == ROADTYPE_TRAM) {
02875 DrawSprite(SPR_TRAMWAY_TRAM + (t->ground.sprite == SPR_ROAD_PAVED_STRAIGHT_X ? 1 : 0), PAL_NONE, x, y);
02876 }
02877
02878
02879 DrawRailTileSeqInGUI(x, y, t, st == STATION_WAYPOINT ? 0 : total_offset, 0, pal);
02880 }
02881
02882 static int GetSlopePixelZ_Station(TileIndex tile, uint x, uint y)
02883 {
02884 return GetTileMaxPixelZ(tile);
02885 }
02886
02887 static Foundation GetFoundation_Station(TileIndex tile, Slope tileh)
02888 {
02889 return FlatteningFoundation(tileh);
02890 }
02891
02892 static void GetTileDesc_Station(TileIndex tile, TileDesc *td)
02893 {
02894 td->owner[0] = GetTileOwner(tile);
02895 if (IsDriveThroughStopTile(tile)) {
02896 Owner road_owner = INVALID_OWNER;
02897 Owner tram_owner = INVALID_OWNER;
02898 RoadTypes rts = GetRoadTypes(tile);
02899 if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
02900 if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
02901
02902
02903 if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
02904 (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
02905 uint i = 1;
02906 if (road_owner != INVALID_OWNER) {
02907 td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
02908 td->owner[i] = road_owner;
02909 i++;
02910 }
02911 if (tram_owner != INVALID_OWNER) {
02912 td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
02913 td->owner[i] = tram_owner;
02914 }
02915 }
02916 }
02917 td->build_date = BaseStation::GetByTile(tile)->build_date;
02918
02919 if (HasStationTileRail(tile)) {
02920 const StationSpec *spec = GetStationSpec(tile);
02921
02922 if (spec != NULL) {
02923 td->station_class = StationClass::Get(spec->cls_id)->name;
02924 td->station_name = spec->name;
02925
02926 if (spec->grf_prop.grffile != NULL) {
02927 const GRFConfig *gc = GetGRFConfig(spec->grf_prop.grffile->grfid);
02928 td->grf = gc->GetName();
02929 }
02930 }
02931
02932 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
02933 td->rail_speed = rti->max_speed;
02934 }
02935
02936 if (IsAirport(tile)) {
02937 const AirportSpec *as = Station::GetByTile(tile)->airport.GetSpec();
02938 td->airport_class = AirportClass::Get(as->cls_id)->name;
02939 td->airport_name = as->name;
02940
02941 const AirportTileSpec *ats = AirportTileSpec::GetByTile(tile);
02942 td->airport_tile_name = ats->name;
02943
02944 if (as->grf_prop.grffile != NULL) {
02945 const GRFConfig *gc = GetGRFConfig(as->grf_prop.grffile->grfid);
02946 td->grf = gc->GetName();
02947 } else if (ats->grf_prop.grffile != NULL) {
02948 const GRFConfig *gc = GetGRFConfig(ats->grf_prop.grffile->grfid);
02949 td->grf = gc->GetName();
02950 }
02951 }
02952
02953 StringID str;
02954 switch (GetStationType(tile)) {
02955 default: NOT_REACHED();
02956 case STATION_RAIL: str = STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION; break;
02957 case STATION_AIRPORT:
02958 str = (IsHangar(tile) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR : STR_LAI_STATION_DESCRIPTION_AIRPORT);
02959 break;
02960 case STATION_TRUCK: str = STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA; break;
02961 case STATION_BUS: str = STR_LAI_STATION_DESCRIPTION_BUS_STATION; break;
02962 case STATION_OILRIG: str = STR_INDUSTRY_NAME_OIL_RIG; break;
02963 case STATION_DOCK: str = STR_LAI_STATION_DESCRIPTION_SHIP_DOCK; break;
02964 case STATION_BUOY: str = STR_LAI_STATION_DESCRIPTION_BUOY; break;
02965 case STATION_WAYPOINT: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
02966 }
02967 td->str = str;
02968 }
02969
02970
02971 static TrackStatus GetTileTrackStatus_Station(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
02972 {
02973 TrackBits trackbits = TRACK_BIT_NONE;
02974
02975 switch (mode) {
02976 case TRANSPORT_RAIL:
02977 if (HasStationRail(tile) && !IsStationTileBlocked(tile)) {
02978 trackbits = TrackToTrackBits(GetRailStationTrack(tile));
02979 }
02980 break;
02981
02982 case TRANSPORT_WATER:
02983
02984 if (IsBuoy(tile)) {
02985 trackbits = TRACK_BIT_ALL;
02986
02987 if (TileX(tile) == 0) trackbits &= ~(TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT);
02988
02989 if (TileY(tile) == 0) trackbits &= ~(TRACK_BIT_Y | TRACK_BIT_LEFT | TRACK_BIT_UPPER);
02990 }
02991 break;
02992
02993 case TRANSPORT_ROAD:
02994 if ((GetRoadTypes(tile) & sub_mode) != 0 && IsRoadStop(tile)) {
02995 DiagDirection dir = GetRoadStopDir(tile);
02996 Axis axis = DiagDirToAxis(dir);
02997
02998 if (side != INVALID_DIAGDIR) {
02999 if (axis != DiagDirToAxis(side) || (IsStandardRoadStopTile(tile) && dir != side)) break;
03000 }
03001
03002 trackbits = AxisToTrackBits(axis);
03003 }
03004 break;
03005
03006 default:
03007 break;
03008 }
03009
03010 return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits), TRACKDIR_BIT_NONE);
03011 }
03012
03013
03014 static void TileLoop_Station(TileIndex tile)
03015 {
03016
03017
03018 switch (GetStationType(tile)) {
03019 case STATION_AIRPORT:
03020 AirportTileAnimationTrigger(Station::GetByTile(tile), tile, AAT_TILELOOP);
03021 break;
03022
03023 case STATION_DOCK:
03024 if (GetTileSlope(tile) != SLOPE_FLAT) break;
03025
03026 case STATION_OILRIG:
03027 case STATION_BUOY:
03028 TileLoop_Water(tile);
03029 break;
03030
03031 default: break;
03032 }
03033 }
03034
03035
03036 static void AnimateTile_Station(TileIndex tile)
03037 {
03038 if (HasStationRail(tile)) {
03039 AnimateStationTile(tile);
03040 return;
03041 }
03042
03043 if (IsAirport(tile)) {
03044 AnimateAirportTile(tile);
03045 }
03046 }
03047
03048
03049 static bool ClickTile_Station(TileIndex tile)
03050 {
03051 const BaseStation *bst = BaseStation::GetByTile(tile);
03052
03053 if (bst->facilities & FACIL_WAYPOINT) {
03054 ShowWaypointWindow(Waypoint::From(bst));
03055 } else if (IsHangar(tile)) {
03056 const Station *st = Station::From(bst);
03057 ShowDepotWindow(st->airport.GetHangarTile(st->airport.GetHangarNum(tile)), VEH_AIRCRAFT);
03058 } else {
03059 ShowStationViewWindow(bst->index);
03060 }
03061 return true;
03062 }
03063
03064 static VehicleEnterTileStatus VehicleEnter_Station(Vehicle *v, TileIndex tile, int x, int y)
03065 {
03066 if (v->type == VEH_TRAIN) {
03067 StationID station_id = GetStationIndex(tile);
03068 if (!v->current_order.ShouldStopAtStation(v, station_id)) return VETSB_CONTINUE;
03069 if (!IsRailStation(tile) || !v->IsFrontEngine()) return VETSB_CONTINUE;
03070
03071 int station_ahead;
03072 int station_length;
03073 int stop = GetTrainStopLocation(station_id, tile, Train::From(v), &station_ahead, &station_length);
03074
03075
03076
03077
03078
03079 if (!IsInsideBS(stop + station_ahead, station_length, TILE_SIZE)) return VETSB_CONTINUE;
03080
03081 DiagDirection dir = DirToDiagDir(v->direction);
03082
03083 x &= 0xF;
03084 y &= 0xF;
03085
03086 if (DiagDirToAxis(dir) != AXIS_X) Swap(x, y);
03087 if (y == TILE_SIZE / 2) {
03088 if (dir != DIAGDIR_SE && dir != DIAGDIR_SW) x = TILE_SIZE - 1 - x;
03089 stop &= TILE_SIZE - 1;
03090
03091 if (x == stop) return VETSB_ENTERED_STATION | (VehicleEnterTileStatus)(station_id << VETS_STATION_ID_OFFSET);
03092 if (x < stop) {
03093 uint16 spd;
03094
03095 v->vehstatus |= VS_TRAIN_SLOWING;
03096 spd = max(0, (stop - x) * 20 - 15);
03097 if (spd < v->cur_speed) v->cur_speed = spd;
03098 }
03099 }
03100 } else if (v->type == VEH_ROAD) {
03101 RoadVehicle *rv = RoadVehicle::From(v);
03102 if (rv->state < RVSB_IN_ROAD_STOP && !IsReversingRoadTrackdir((Trackdir)rv->state) && rv->frame == 0) {
03103 if (IsRoadStop(tile) && rv->IsFrontEngine()) {
03104
03105 return RoadStop::GetByTile(tile, GetRoadStopType(tile))->Enter(rv) ? VETSB_CONTINUE : VETSB_CANNOT_ENTER;
03106 }
03107 }
03108 }
03109
03110 return VETSB_CONTINUE;
03111 }
03112
03117 void TriggerWatchedCargoCallbacks(Station *st)
03118 {
03119
03120 uint cargoes = 0;
03121 for (CargoID cid = 0; cid < NUM_CARGO; cid++) {
03122 if (HasBit(st->goods[cid].acceptance_pickup, GoodsEntry::GES_ACCEPTED_BIGTICK)) SetBit(cargoes, cid);
03123 }
03124
03125
03126 if (cargoes == 0) return;
03127
03128
03129 Rect r = st->GetCatchmentRect();
03130 TileArea ta(TileXY(r.left, r.top), TileXY(r.right, r.bottom));
03131 TILE_AREA_LOOP(tile, ta) {
03132 if (IsTileType(tile, MP_HOUSE)) {
03133 WatchedCargoCallback(tile, cargoes);
03134 }
03135 }
03136 }
03137
03144 static bool StationHandleBigTick(BaseStation *st)
03145 {
03146 if (!st->IsInUse()) {
03147 if (++st->delete_ctr >= 8) delete st;
03148 return false;
03149 }
03150
03151 if (Station::IsExpected(st)) {
03152 TriggerWatchedCargoCallbacks(Station::From(st));
03153
03154 for (CargoID i = 0; i < NUM_CARGO; i++) {
03155 ClrBit(Station::From(st)->goods[i].acceptance_pickup, GoodsEntry::GES_ACCEPTED_BIGTICK);
03156 }
03157 }
03158
03159
03160 if ((st->facilities & FACIL_WAYPOINT) == 0) UpdateStationAcceptance(Station::From(st), true);
03161
03162 return true;
03163 }
03164
03165 static inline void byte_inc_sat(byte *p)
03166 {
03167 byte b = *p + 1;
03168 if (b != 0) *p = b;
03169 }
03170
03171 static void UpdateStationRating(Station *st)
03172 {
03173 bool waiting_changed = false;
03174
03175 byte_inc_sat(&st->time_since_load);
03176 byte_inc_sat(&st->time_since_unload);
03177
03178 const CargoSpec *cs;
03179 FOR_ALL_CARGOSPECS(cs) {
03180 GoodsEntry *ge = &st->goods[cs->Index()];
03181
03182
03183
03184 if (!HasBit(ge->acceptance_pickup, GoodsEntry::GES_PICKUP) && ge->rating < INITIAL_STATION_RATING) {
03185 ge->rating++;
03186 }
03187
03188
03189 if (HasBit(ge->acceptance_pickup, GoodsEntry::GES_PICKUP)) {
03190 byte_inc_sat(&ge->time_since_pickup);
03191
03192 bool skip = false;
03193 int rating = 0;
03194 uint waiting = ge->cargo.Count();
03195
03196
03197
03198
03199 uint num_dests = (uint)ge->cargo.Packets()->MapSize();
03200
03201
03202
03203
03204
03205
03206
03207 uint waiting_avg = waiting / (num_dests + 1);
03208
03209 if (HasBit(cs->callback_mask, CBM_CARGO_STATION_RATING_CALC)) {
03210
03211
03212
03213
03214 uint last_speed = ge->HasVehicleEverTriedLoading() ? ge->last_speed : 0xFF;
03215
03216 uint32 var18 = min(ge->time_since_pickup, 0xFF) | (min(ge->max_waiting_cargo, 0xFFFF) << 8) | (min(last_speed, 0xFF) << 24);
03217
03218 uint32 var10 = (st->last_vehicle_type == VEH_INVALID) ? 0x0 : (st->last_vehicle_type + 0x10);
03219 uint16 callback = GetCargoCallback(CBID_CARGO_STATION_RATING_CALC, var10, var18, cs);
03220 if (callback != CALLBACK_FAILED) {
03221 skip = true;
03222 rating = GB(callback, 0, 14);
03223
03224
03225 if (HasBit(callback, 14)) rating -= 0x4000;
03226 }
03227 }
03228
03229 if (!skip) {
03230 int b = ge->last_speed - 85;
03231 if (b >= 0) rating += b >> 2;
03232
03233 byte waittime = ge->time_since_pickup;
03234 if (st->last_vehicle_type == VEH_SHIP) waittime >>= 2;
03235 (waittime > 21) ||
03236 (rating += 25, waittime > 12) ||
03237 (rating += 25, waittime > 6) ||
03238 (rating += 45, waittime > 3) ||
03239 (rating += 35, true);
03240
03241 (rating -= 90, ge->max_waiting_cargo > 1500) ||
03242 (rating += 55, ge->max_waiting_cargo > 1000) ||
03243 (rating += 35, ge->max_waiting_cargo > 600) ||
03244 (rating += 10, ge->max_waiting_cargo > 300) ||
03245 (rating += 20, ge->max_waiting_cargo > 100) ||
03246 (rating += 10, true);
03247 }
03248
03249 if (Company::IsValidID(st->owner) && HasBit(st->town->statues, st->owner)) rating += 26;
03250
03251 byte age = ge->last_age;
03252 (age >= 3) ||
03253 (rating += 10, age >= 2) ||
03254 (rating += 10, age >= 1) ||
03255 (rating += 13, true);
03256
03257 {
03258 int or_ = ge->rating;
03259
03260
03261 ge->rating = rating = or_ + Clamp(Clamp(rating, 0, 255) - or_, -2, 2);
03262
03263
03264
03265 if (rating <= 64 && waiting_avg >= 100) {
03266 int dec = Random() & 0x1F;
03267 if (waiting_avg < 200) dec &= 7;
03268 waiting -= (dec + 1) * num_dests;
03269 waiting_changed = true;
03270 }
03271
03272
03273 if (rating <= 127 && waiting != 0) {
03274 uint32 r = Random();
03275 if (rating <= (int)GB(r, 0, 7)) {
03276
03277 waiting = max((int)waiting - (int)((GB(r, 8, 2) - 1) * num_dests), 0);
03278 waiting_changed = true;
03279 }
03280 }
03281
03282
03283
03284
03285 static const uint WAITING_CARGO_THRESHOLD = 1 << 12;
03286 static const uint WAITING_CARGO_CUT_FACTOR = 1 << 6;
03287 static const uint MAX_WAITING_CARGO = 1 << 15;
03288
03289 if (waiting > WAITING_CARGO_THRESHOLD) {
03290 uint difference = waiting - WAITING_CARGO_THRESHOLD;
03291 waiting -= (difference / WAITING_CARGO_CUT_FACTOR);
03292
03293 waiting = min(waiting, MAX_WAITING_CARGO);
03294 waiting_changed = true;
03295 }
03296
03297 if (waiting_changed) {
03298
03299
03300
03301 ge->max_waiting_cargo = 0;
03302
03303
03304
03305
03306 StationCargoAmountMap waiting_per_source;
03307 ge->cargo.CountAndTruncate(waiting, waiting_per_source);
03308 for (StationCargoAmountMap::iterator i(waiting_per_source.begin()); i != waiting_per_source.end(); ++i) {
03309 Station *source_station = Station::GetIfValid(i->first);
03310 if (source_station == NULL) continue;
03311
03312 GoodsEntry &source_ge = source_station->goods[cs->Index()];
03313 source_ge.max_waiting_cargo = max(source_ge.max_waiting_cargo, i->second);
03314 }
03315 } else {
03316
03317 ge->max_waiting_cargo = waiting_avg;
03318 }
03319 }
03320 }
03321 }
03322
03323 StationID index = st->index;
03324 if (waiting_changed) {
03325 SetWindowDirty(WC_STATION_VIEW, index);
03326 } else {
03327 SetWindowWidgetDirty(WC_STATION_VIEW, index, WID_SV_ACCEPT_RATING_LIST);
03328 }
03329 }
03330
03337 void DeleteStaleFlows(StationID at, CargoID c_id, StationID to)
03338 {
03339 FlowStatMap &flows = Station::Get(at)->goods[c_id].flows;
03340 for (FlowStatMap::iterator f_it = flows.begin(); f_it != flows.end();) {
03341 FlowStat &s_flows = f_it->second;
03342 s_flows.EraseShare(to);
03343 if (s_flows.GetShares()->empty()) {
03344 flows.erase(f_it++);
03345 } else {
03346 ++f_it;
03347 }
03348 }
03349 }
03350
03357 uint GetMovingAverageLength(const Station *from, const Station *to)
03358 {
03359 return LinkStat::MIN_DISTANCE + (DistanceManhattan(from->xy, to->xy) >> 2);
03360 }
03361
03365 void Station::RunAverages()
03366 {
03367 for (int goods_index = 0; goods_index < NUM_CARGO; ++goods_index) {
03368 LinkStatMap &links = this->goods[goods_index].link_stats;
03369 for (LinkStatMap::iterator i = links.begin(); i != links.end();) {
03370 StationID id = i->first;
03371 if (Station::IsValidID(id)) {
03372 i->second.Decrease();
03373 if (i->second.IsValid()) {
03374 ++i;
03375 } else {
03376 DeleteStaleFlows(this->index, goods_index, id);
03377 this->goods[goods_index].cargo.RerouteStalePackets(id);
03378 links.erase(i++);
03379 }
03380 } else {
03381 this->goods[goods_index].cargo.RerouteStalePackets(id);
03382 links.erase(i++);
03383 }
03384 }
03385
03386 if (_settings_game.linkgraph.GetDistributionType(goods_index) == DT_MANUAL) {
03387 this->goods[goods_index].flows.clear();
03388 }
03389 }
03390 }
03391
03400 void IncreaseStats(Station *st, CargoID cargo, StationID next_station_id, uint capacity, uint usage)
03401 {
03402 LinkStatMap &stats = st->goods[cargo].link_stats;
03403 LinkStatMap::iterator i = stats.find(next_station_id);
03404 if (i == stats.end()) {
03405 assert(st->index != next_station_id);
03406 stats.insert(std::make_pair(next_station_id, LinkStat(
03407 GetMovingAverageLength(st,
03408 Station::Get(next_station_id)), capacity,
03409 usage == UINT_MAX ? 0 : usage)));
03410 } else {
03411 if (usage == UINT_MAX) {
03412 i->second.Refresh(capacity);
03413 } else {
03414 assert(capacity >= usage);
03415 i->second.Increase(capacity, usage);
03416 }
03417 assert(i->second.IsValid());
03418 }
03419 }
03420
03427 void IncreaseStats(Station *st, const Vehicle *front, StationID next_station_id)
03428 {
03429 for (const Vehicle *v = front; v != NULL; v = v->Next()) {
03430 if (v->refit_cap > 0) {
03431
03432
03433
03434
03435
03436
03437 IncreaseStats(st, v->cargo_type, next_station_id, v->refit_cap,
03438 min(v->refit_cap, v->cargo.Count()));
03439 }
03440 }
03441 }
03442
03443
03444 static void StationHandleSmallTick(BaseStation *st)
03445 {
03446 if ((st->facilities & FACIL_WAYPOINT) != 0 || !st->IsInUse()) return;
03447
03448 byte b = st->delete_ctr + 1;
03449 if (b >= STATION_RATING_TICKS) b = 0;
03450 st->delete_ctr = b;
03451
03452 if (b == 0) UpdateStationRating(Station::From(st));
03453 }
03454
03455 void OnTick_Station()
03456 {
03457 if (_game_mode == GM_EDITOR) return;
03458
03459 for (uint id = _tick_counter % DAY_TICKS; id < Station::GetPoolSize(); id += DAY_TICKS) {
03460 Station *item = Station::GetIfValid(id);
03461 if (item != NULL) item->RunAverages();
03462 }
03463
03464 BaseStation *st;
03465 FOR_ALL_BASE_STATIONS(st) {
03466 StationHandleSmallTick(st);
03467
03468
03469
03470
03471 if ((_tick_counter + st->index) % STATION_ACCEPTANCE_TICKS == 0) {
03472
03473 if (!StationHandleBigTick(st)) continue;
03474 TriggerStationAnimation(st, st->xy, SAT_250_TICKS);
03475 if (Station::IsExpected(st)) AirportAnimationTrigger(Station::From(st), AAT_STATION_250_TICKS);
03476 }
03477 }
03478 }
03479
03481 void StationMonthlyLoop()
03482 {
03483 Station *st;
03484
03485 FOR_ALL_STATIONS(st) {
03486 for (CargoID i = 0; i < NUM_CARGO; i++) {
03487 GoodsEntry *ge = &st->goods[i];
03488 SB(ge->acceptance_pickup, GoodsEntry::GES_LAST_MONTH, 1, GB(ge->acceptance_pickup, GoodsEntry::GES_CURRENT_MONTH, 1));
03489 ClrBit(ge->acceptance_pickup, GoodsEntry::GES_CURRENT_MONTH);
03490 ge->supply = ge->supply_new;
03491 ge->supply_new = 0;
03492 }
03493 }
03494 }
03495
03496
03497 void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
03498 {
03499 Station *st;
03500
03501 FOR_ALL_STATIONS(st) {
03502 if (st->owner == owner &&
03503 DistanceManhattan(tile, st->xy) <= radius) {
03504 for (CargoID i = 0; i < NUM_CARGO; i++) {
03505 GoodsEntry *ge = &st->goods[i];
03506
03507 if (ge->acceptance_pickup != 0) {
03508 ge->rating = Clamp(ge->rating + amount, 0, 255);
03509 }
03510 }
03511 }
03512 }
03513 }
03514
03515 static uint UpdateStationWaiting(Station *st, CargoID type, uint amount, SourceType source_type, SourceID source_id)
03516 {
03517
03518
03519 if (!CargoPacket::CanAllocateItem()) return 0;
03520
03521 GoodsEntry &ge = st->goods[type];
03522 amount += ge.amount_fract;
03523 ge.amount_fract = GB(amount, 0, 8);
03524
03525 amount >>= 8;
03526
03527 if (amount == 0) return 0;
03528
03529 StationID next = ge.GetVia(st->index);
03530
03531 ge.cargo.Append(next, new CargoPacket(st->index, st->xy, amount, source_type, source_id));
03532 ge.supply_new += amount;
03533
03534 if (!HasBit(ge.acceptance_pickup, GoodsEntry::GES_PICKUP)) {
03535 InvalidateWindowData(WC_STATION_LIST, st->index);
03536 SetBit(ge.acceptance_pickup, GoodsEntry::GES_PICKUP);
03537 }
03538
03539 TriggerStationAnimation(st, st->xy, SAT_NEW_CARGO, type);
03540 AirportAnimationTrigger(st, AAT_STATION_NEW_CARGO, type);
03541
03542 SetWindowDirty(WC_STATION_VIEW, st->index);
03543 st->MarkTilesDirty(true);
03544 return amount;
03545 }
03546
03547 static bool IsUniqueStationName(const char *name)
03548 {
03549 const Station *st;
03550
03551 FOR_ALL_STATIONS(st) {
03552 if (st->name != NULL && strcmp(st->name, name) == 0) return false;
03553 }
03554
03555 return true;
03556 }
03557
03567 CommandCost CmdRenameStation(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
03568 {
03569 Station *st = Station::GetIfValid(p1);
03570 if (st == NULL) return CMD_ERROR;
03571
03572 CommandCost ret = CheckOwnership(st->owner);
03573 if (ret.Failed()) return ret;
03574
03575 bool reset = StrEmpty(text);
03576
03577 if (!reset) {
03578 if (Utf8StringLength(text) >= MAX_LENGTH_STATION_NAME_CHARS) return CMD_ERROR;
03579 if (!IsUniqueStationName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
03580 }
03581
03582 if (flags & DC_EXEC) {
03583 free(st->name);
03584 st->name = reset ? NULL : strdup(text);
03585
03586 st->UpdateVirtCoord();
03587 InvalidateWindowData(WC_STATION_LIST, st->owner, 1);
03588 }
03589
03590 return CommandCost();
03591 }
03592
03599 void FindStationsAroundTiles(const TileArea &location, StationList *stations)
03600 {
03601
03602 uint max_rad = (_settings_game.station.modified_catchment ? MAX_CATCHMENT : CA_UNMODIFIED);
03603
03604 uint x = TileX(location.tile);
03605 uint y = TileY(location.tile);
03606
03607 uint min_x = (x > max_rad) ? x - max_rad : 0;
03608 uint max_x = x + location.w + max_rad;
03609 uint min_y = (y > max_rad) ? y - max_rad : 0;
03610 uint max_y = y + location.h + max_rad;
03611
03612 if (min_x == 0 && _settings_game.construction.freeform_edges) min_x = 1;
03613 if (min_y == 0 && _settings_game.construction.freeform_edges) min_y = 1;
03614 if (max_x >= MapSizeX()) max_x = MapSizeX() - 1;
03615 if (max_y >= MapSizeY()) max_y = MapSizeY() - 1;
03616
03617 for (uint cy = min_y; cy < max_y; cy++) {
03618 for (uint cx = min_x; cx < max_x; cx++) {
03619 TileIndex cur_tile = TileXY(cx, cy);
03620 if (!IsTileType(cur_tile, MP_STATION)) continue;
03621
03622 Station *st = Station::GetByTile(cur_tile);
03623
03624 if (st == NULL) continue;
03625
03626 if (_settings_game.station.modified_catchment) {
03627 int rad = st->GetCatchmentRadius();
03628 int rad_x = cx - x;
03629 int rad_y = cy - y;
03630
03631 if (rad_x < -rad || rad_x >= rad + location.w) continue;
03632 if (rad_y < -rad || rad_y >= rad + location.h) continue;
03633 }
03634
03635
03636
03637
03638 stations->Include(st);
03639 }
03640 }
03641 }
03642
03647 const StationList *StationFinder::GetStations()
03648 {
03649 if (this->tile != INVALID_TILE) {
03650 FindStationsAroundTiles(*this, &this->stations);
03651 this->tile = INVALID_TILE;
03652 }
03653 return &this->stations;
03654 }
03655
03656 uint MoveGoodsToStation(CargoID type, uint amount, SourceType source_type, SourceID source_id, const StationList *all_stations)
03657 {
03658
03659 if (amount == 0) return 0;
03660
03661 Station *st1 = NULL;
03662 Station *st2 = NULL;
03663 uint best_rating1 = 0;
03664 uint best_rating2 = 0;
03665
03666 for (Station * const *st_iter = all_stations->Begin(); st_iter != all_stations->End(); ++st_iter) {
03667 Station *st = *st_iter;
03668
03669
03670 if (st->town->exclusive_counter > 0 && st->town->exclusivity != st->owner) continue;
03671
03672 if (st->goods[type].rating == 0) continue;
03673
03674 if (_settings_game.order.selectgoods && !st->goods[type].HasVehicleEverTriedLoading()) continue;
03675
03676 if (IsCargoInClass(type, CC_PASSENGERS)) {
03677 if (st->facilities == FACIL_TRUCK_STOP) continue;
03678 } else {
03679 if (st->facilities == FACIL_BUS_STOP) continue;
03680 }
03681
03682
03683 if (st1 == NULL || st->goods[type].rating >= best_rating1) {
03684 st2 = st1; best_rating2 = best_rating1; st1 = st; best_rating1 = st->goods[type].rating;
03685 } else if (st2 == NULL || st->goods[type].rating >= best_rating2) {
03686 st2 = st; best_rating2 = st->goods[type].rating;
03687 }
03688 }
03689
03690
03691 if (st1 == NULL) return 0;
03692
03693
03694
03695 amount *= best_rating1 + 1;
03696
03697 if (st2 == NULL) {
03698
03699 return UpdateStationWaiting(st1, type, amount, source_type, source_id);
03700 }
03701
03702
03703 assert(st1 != NULL);
03704 assert(st2 != NULL);
03705 assert(best_rating1 != 0 || best_rating2 != 0);
03706
03707
03708
03709
03710
03711
03712 uint worst_cargo = amount * best_rating2 / (best_rating1 + best_rating2);
03713 assert(worst_cargo <= (amount - worst_cargo));
03714
03715
03716 uint moved = UpdateStationWaiting(st1, type, amount - worst_cargo, source_type, source_id);
03717
03718
03719 return moved + UpdateStationWaiting(st2, type, worst_cargo, source_type, source_id);
03720 }
03721
03722 void BuildOilRig(TileIndex tile)
03723 {
03724 if (!Station::CanAllocateItem()) {
03725 DEBUG(misc, 0, "Can't allocate station for oilrig at 0x%X, reverting to oilrig only", tile);
03726 return;
03727 }
03728
03729 Station *st = new Station(tile);
03730 st->town = ClosestTownFromTile(tile, UINT_MAX);
03731
03732 st->string_id = GenerateStationName(st, tile, STATIONNAMING_OILRIG);
03733
03734 assert(IsTileType(tile, MP_INDUSTRY));
03735 DeleteAnimatedTile(tile);
03736 MakeOilrig(tile, st->index, GetWaterClass(tile));
03737
03738 st->owner = OWNER_NONE;
03739 st->airport.type = AT_OILRIG;
03740 st->airport.Add(tile);
03741 st->dock_tile = tile;
03742 st->facilities = FACIL_AIRPORT | FACIL_DOCK;
03743 st->build_date = _date;
03744
03745 st->rect.BeforeAddTile(tile, StationRect::ADD_FORCE);
03746
03747 st->UpdateVirtCoord();
03748 UpdateStationAcceptance(st, false);
03749 st->RecomputeIndustriesNear();
03750 }
03751
03752 void DeleteOilRig(TileIndex tile)
03753 {
03754 Station *st = Station::GetByTile(tile);
03755
03756 MakeWaterKeepingClass(tile, OWNER_NONE);
03757
03758 st->dock_tile = INVALID_TILE;
03759 st->airport.Clear();
03760 st->facilities &= ~(FACIL_AIRPORT | FACIL_DOCK);
03761 st->airport.flags = 0;
03762
03763 st->rect.AfterRemoveTile(st, tile);
03764
03765 st->UpdateVirtCoord();
03766 st->RecomputeIndustriesNear();
03767 if (!st->IsInUse()) delete st;
03768 }
03769
03770 static void ChangeTileOwner_Station(TileIndex tile, Owner old_owner, Owner new_owner)
03771 {
03772 if (IsRoadStopTile(tile)) {
03773 for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
03774
03775 if (GetRoadOwner(tile, rt) == old_owner) {
03776 if (HasTileRoadType(tile, rt)) {
03777
03778 Company::Get(old_owner)->infrastructure.road[rt] -= 2;
03779 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.road[rt] += 2;
03780 }
03781 SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
03782 }
03783 }
03784 }
03785
03786 if (!IsTileOwner(tile, old_owner)) return;
03787
03788 if (new_owner != INVALID_OWNER) {
03789
03790
03791
03792
03793 Company *old_company = Company::Get(old_owner);
03794 Company *new_company = Company::Get(new_owner);
03795
03796
03797 switch (GetStationType(tile)) {
03798 case STATION_RAIL:
03799 case STATION_WAYPOINT:
03800 if (!IsStationTileBlocked(tile)) {
03801 old_company->infrastructure.rail[GetRailType(tile)]--;
03802 new_company->infrastructure.rail[GetRailType(tile)]++;
03803 }
03804 break;
03805
03806 case STATION_BUS:
03807 case STATION_TRUCK:
03808
03809 break;
03810
03811 case STATION_BUOY:
03812 case STATION_DOCK:
03813 if (GetWaterClass(tile) == WATER_CLASS_CANAL) {
03814 old_company->infrastructure.water--;
03815 new_company->infrastructure.water++;
03816 }
03817 break;
03818
03819 default:
03820 break;
03821 }
03822
03823
03824 if (!IsBuoy(tile) && !IsAirport(tile)) {
03825 old_company->infrastructure.station--;
03826 new_company->infrastructure.station++;
03827 }
03828
03829
03830 SetTileOwner(tile, new_owner);
03831 InvalidateWindowClassesData(WC_STATION_LIST, 0);
03832 } else {
03833 if (IsDriveThroughStopTile(tile)) {
03834
03835 DoCommand(tile, 1 | 1 << 8, (GetStationType(tile) == STATION_TRUCK) ? ROADSTOP_TRUCK : ROADSTOP_BUS, DC_EXEC | DC_BANKRUPT, CMD_REMOVE_ROAD_STOP);
03836 assert(IsTileType(tile, MP_ROAD));
03837
03838 ChangeTileOwner(tile, old_owner, new_owner);
03839 } else {
03840 DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
03841
03842
03843
03844 if ((IsTileType(tile, MP_WATER) || IsBuoyTile(tile)) && IsTileOwner(tile, old_owner)) SetTileOwner(tile, OWNER_NONE);
03845 }
03846 }
03847 }
03848
03857 static bool CanRemoveRoadWithStop(TileIndex tile, DoCommandFlag flags)
03858 {
03859
03860 if (_current_company == OWNER_WATER) return true;
03861
03862 RoadTypes rts = GetRoadTypes(tile);
03863 if (HasBit(rts, ROADTYPE_TRAM)) {
03864 Owner tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
03865 if (tram_owner != OWNER_NONE && CheckOwnership(tram_owner).Failed()) return false;
03866 }
03867 if (HasBit(rts, ROADTYPE_ROAD)) {
03868 Owner road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
03869 if (road_owner != OWNER_TOWN) {
03870 if (road_owner != OWNER_NONE && CheckOwnership(road_owner).Failed()) return false;
03871 } else {
03872 if (CheckAllowRemoveRoad(tile, GetAnyRoadBits(tile, ROADTYPE_ROAD), OWNER_TOWN, ROADTYPE_ROAD, flags).Failed()) return false;
03873 }
03874 }
03875
03876 return true;
03877 }
03878
03885 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags)
03886 {
03887 if (flags & DC_AUTO) {
03888 switch (GetStationType(tile)) {
03889 default: break;
03890 case STATION_RAIL: return_cmd_error(STR_ERROR_MUST_DEMOLISH_RAILROAD);
03891 case STATION_WAYPOINT: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
03892 case STATION_AIRPORT: return_cmd_error(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST);
03893 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);
03894 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);
03895 case STATION_BUOY: return_cmd_error(STR_ERROR_BUOY_IN_THE_WAY);
03896 case STATION_DOCK: return_cmd_error(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST);
03897 case STATION_OILRIG:
03898 SetDParam(1, STR_INDUSTRY_NAME_OIL_RIG);
03899 return_cmd_error(STR_ERROR_GENERIC_OBJECT_IN_THE_WAY);
03900 }
03901 }
03902
03903 switch (GetStationType(tile)) {
03904 case STATION_RAIL: return RemoveRailStation(tile, flags);
03905 case STATION_WAYPOINT: return RemoveRailWaypoint(tile, flags);
03906 case STATION_AIRPORT: return RemoveAirport(tile, flags);
03907 case STATION_TRUCK:
03908 if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
03909 return_cmd_error(STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
03910 }
03911 return RemoveRoadStop(tile, flags);
03912 case STATION_BUS:
03913 if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
03914 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
03915 }
03916 return RemoveRoadStop(tile, flags);
03917 case STATION_BUOY: return RemoveBuoy(tile, flags);
03918 case STATION_DOCK: return RemoveDock(tile, flags);
03919 default: break;
03920 }
03921
03922 return CMD_ERROR;
03923 }
03924
03925 static CommandCost TerraformTile_Station(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
03926 {
03927 if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
03928
03929
03930
03931 if (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new)) {
03932 switch (GetStationType(tile)) {
03933 case STATION_WAYPOINT:
03934 case STATION_RAIL: {
03935 DiagDirection direction = AxisToDiagDir(GetRailStationAxis(tile));
03936 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
03937 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
03938 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
03939 }
03940
03941 case STATION_AIRPORT:
03942 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
03943
03944 case STATION_TRUCK:
03945 case STATION_BUS: {
03946 DiagDirection direction = GetRoadStopDir(tile);
03947 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
03948 if (IsDriveThroughStopTile(tile)) {
03949 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
03950 }
03951 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
03952 }
03953
03954 default: break;
03955 }
03956 }
03957 }
03958 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
03959 }
03960
03966 uint FlowStat::GetShare(StationID st) const
03967 {
03968 uint32 prev = 0;
03969 for (SharesMap::const_iterator it = this->shares.begin(); it != this->shares.end(); ++it) {
03970 if (it->second == st) {
03971 return it->first - prev;
03972 } else {
03973 prev = it->first;
03974 }
03975 }
03976 return 0;
03977 }
03978
03984 StationID FlowStat::GetVia(StationID excluded) const
03985 {
03986 assert(!this->shares.empty());
03987 uint max = (--this->shares.end())->first - 1;
03988 SharesMap::const_iterator it = this->shares.upper_bound(RandomRange(max));
03989 assert(it != this->shares.end());
03990 if (it->second != excluded) {
03991 return it->second;
03992 } else {
03993 uint end = it->first;
03994 if (end - 1 == max) return INVALID_STATION;
03995 uint begin = (it == this->shares.begin() ? 0 : (--it)->first);
03996 uint rand = RandomRange(max - (end - begin));
03997 if (rand < begin) {
03998 return this->shares.upper_bound(rand)->second;
03999 } else {
04000 return this->shares.upper_bound(rand + (end - begin))->second;
04001 }
04002 }
04003 }
04004
04009 void FlowStat::EraseShare(StationID st)
04010 {
04011 uint32 removed_shares = 0;
04012 uint32 last_share = 0;
04013 SharesMap new_shares;
04014 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
04015 if (it->second == st) {
04016 removed_shares += it->first - last_share;
04017 } else {
04018 new_shares[it->first - removed_shares] = it->second;
04019 }
04020 last_share = it->first;
04021 }
04022 this->shares.swap(new_shares);
04023 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
04024 assert(it->second != st);
04025 }
04026 }
04027
04033 uint GoodsEntry::GetSumFlowVia(StationID via) const
04034 {
04035 uint ret = 0;
04036 for (FlowStatMap::const_iterator i = this->flows.begin(); i != this->flows.end(); ++i) {
04037 ret += i->second.GetShare(via);
04038 }
04039 return ret;
04040 }
04041
04042 extern const TileTypeProcs _tile_type_station_procs = {
04043 DrawTile_Station,
04044 GetSlopePixelZ_Station,
04045 ClearTile_Station,
04046 NULL,
04047 GetTileDesc_Station,
04048 GetTileTrackStatus_Station,
04049 ClickTile_Station,
04050 AnimateTile_Station,
04051 TileLoop_Station,
04052 ChangeTileOwner_Station,
04053 NULL,
04054 VehicleEnter_Station,
04055 GetFoundation_Station,
04056 TerraformTile_Station,
04057 };