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 "roadveh.h"
00022 #include "industry.h"
00023 #include "newgrf_cargo.h"
00024 #include "newgrf_debug.h"
00025 #include "newgrf_station.h"
00026 #include "pathfinder/yapf/yapf_cache.h"
00027 #include "road_internal.h"
00028 #include "autoslope.h"
00029 #include "water.h"
00030 #include "station_gui.h"
00031 #include "strings_func.h"
00032 #include "clear_func.h"
00033 #include "window_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 "cargodest_func.h"
00052
00053 #include "table/strings.h"
00054
00061 bool IsHangar(TileIndex t)
00062 {
00063 assert(IsTileType(t, MP_STATION));
00064
00065
00066 if (!IsAirport(t)) return false;
00067
00068 const Station *st = Station::GetByTile(t);
00069 const AirportSpec *as = st->airport.GetSpec();
00070
00071 for (uint i = 0; i < as->nof_depots; i++) {
00072 if (st->airport.GetHangarTile(i) == t) return true;
00073 }
00074
00075 return false;
00076 }
00077
00085 template <class T>
00086 CommandCost GetStationAround(TileArea ta, StationID closest_station, T **st)
00087 {
00088 ta.tile -= TileDiffXY(1, 1);
00089 ta.w += 2;
00090 ta.h += 2;
00091
00092
00093 TILE_AREA_LOOP(tile_cur, ta) {
00094 if (IsTileType(tile_cur, MP_STATION)) {
00095 StationID t = GetStationIndex(tile_cur);
00096 if (!T::IsValidID(t)) continue;
00097
00098 if (closest_station == INVALID_STATION) {
00099 closest_station = t;
00100 } else if (closest_station != t) {
00101 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
00102 }
00103 }
00104 }
00105 *st = (closest_station == INVALID_STATION) ? NULL : T::Get(closest_station);
00106 return CommandCost();
00107 }
00108
00114 typedef bool (*CMSAMatcher)(TileIndex tile);
00115
00122 static int CountMapSquareAround(TileIndex tile, CMSAMatcher cmp)
00123 {
00124 int num = 0;
00125
00126 for (int dx = -3; dx <= 3; dx++) {
00127 for (int dy = -3; dy <= 3; dy++) {
00128 TileIndex t = TileAddWrap(tile, dx, dy);
00129 if (t != INVALID_TILE && cmp(t)) num++;
00130 }
00131 }
00132
00133 return num;
00134 }
00135
00141 static bool CMSAMine(TileIndex tile)
00142 {
00143
00144 if (!IsTileType(tile, MP_INDUSTRY)) return false;
00145
00146 const Industry *ind = Industry::GetByTile(tile);
00147
00148
00149 if ((GetIndustrySpec(ind->type)->life_type & INDUSTRYLIFE_EXTRACTIVE) == 0) return false;
00150
00151 for (uint i = 0; i < lengthof(ind->produced_cargo); i++) {
00152
00153
00154 if (ind->produced_cargo[i] != CT_INVALID &&
00155 (CargoSpec::Get(ind->produced_cargo[i])->classes & (CC_LIQUID | CC_PASSENGERS | CC_MAIL)) == 0) {
00156 return true;
00157 }
00158 }
00159
00160 return false;
00161 }
00162
00168 static bool CMSAWater(TileIndex tile)
00169 {
00170 return IsTileType(tile, MP_WATER) && IsWater(tile);
00171 }
00172
00178 static bool CMSATree(TileIndex tile)
00179 {
00180 return IsTileType(tile, MP_TREES);
00181 }
00182
00188 static bool CMSAForest(TileIndex tile)
00189 {
00190
00191 if (!IsTileType(tile, MP_INDUSTRY)) return false;
00192
00193 const Industry *ind = Industry::GetByTile(tile);
00194
00195
00196 if ((GetIndustrySpec(ind->type)->life_type & INDUSTRYLIFE_ORGANIC) == 0) return false;
00197
00198 for (uint i = 0; i < lengthof(ind->produced_cargo); i++) {
00199
00200 if (ind->produced_cargo[i] != CT_INVALID && CargoSpec::Get(ind->produced_cargo[i])->label == 'WOOD') return true;
00201 }
00202
00203 return false;
00204 }
00205
00206 #define M(x) ((x) - STR_SV_STNAME)
00207
00208 enum StationNaming {
00209 STATIONNAMING_RAIL,
00210 STATIONNAMING_ROAD,
00211 STATIONNAMING_AIRPORT,
00212 STATIONNAMING_OILRIG,
00213 STATIONNAMING_DOCK,
00214 STATIONNAMING_HELIPORT,
00215 };
00216
00218 struct StationNameInformation {
00219 uint32 free_names;
00220 bool *indtypes;
00221 };
00222
00231 static bool FindNearIndustryName(TileIndex tile, void *user_data)
00232 {
00233
00234 StationNameInformation *sni = (StationNameInformation*)user_data;
00235 if (!IsTileType(tile, MP_INDUSTRY)) return false;
00236
00237
00238 IndustryType indtype = GetIndustryType(tile);
00239 if (GetIndustrySpec(indtype)->station_name == STR_UNDEFINED) return false;
00240
00241
00242
00243 sni->free_names &= ~(1 << M(STR_SV_STNAME_OILFIELD) | 1 << M(STR_SV_STNAME_MINES));
00244 return !sni->indtypes[indtype];
00245 }
00246
00247 static StringID GenerateStationName(Station *st, TileIndex tile, StationNaming name_class)
00248 {
00249 static const uint32 _gen_station_name_bits[] = {
00250 0,
00251 0,
00252 1U << M(STR_SV_STNAME_AIRPORT),
00253 1U << M(STR_SV_STNAME_OILFIELD),
00254 1U << M(STR_SV_STNAME_DOCKS),
00255 1U << M(STR_SV_STNAME_HELIPORT),
00256 };
00257
00258 const Town *t = st->town;
00259 uint32 free_names = UINT32_MAX;
00260
00261 bool indtypes[NUM_INDUSTRYTYPES];
00262 memset(indtypes, 0, sizeof(indtypes));
00263
00264 const Station *s;
00265 FOR_ALL_STATIONS(s) {
00266 if (s != st && s->town == t) {
00267 if (s->indtype != IT_INVALID) {
00268 indtypes[s->indtype] = true;
00269 continue;
00270 }
00271 uint str = M(s->string_id);
00272 if (str <= 0x20) {
00273 if (str == M(STR_SV_STNAME_FOREST)) {
00274 str = M(STR_SV_STNAME_WOODS);
00275 }
00276 ClrBit(free_names, str);
00277 }
00278 }
00279 }
00280
00281 TileIndex indtile = tile;
00282 StationNameInformation sni = { free_names, indtypes };
00283 if (CircularTileSearch(&indtile, 7, FindNearIndustryName, &sni)) {
00284
00285 IndustryType indtype = GetIndustryType(indtile);
00286 const IndustrySpec *indsp = GetIndustrySpec(indtype);
00287
00288 if (indsp->station_name != STR_NULL) {
00289 st->indtype = indtype;
00290 return STR_SV_STNAME_FALLBACK;
00291 }
00292 }
00293
00294
00295 free_names = sni.free_names;
00296
00297
00298 uint32 tmp = free_names & _gen_station_name_bits[name_class];
00299 if (tmp != 0) return STR_SV_STNAME + FindFirstBit(tmp);
00300
00301
00302 if (HasBit(free_names, M(STR_SV_STNAME_MINES))) {
00303 if (CountMapSquareAround(tile, CMSAMine) >= 2) {
00304 return STR_SV_STNAME_MINES;
00305 }
00306 }
00307
00308
00309 if (DistanceMax(tile, t->xy) < 8) {
00310 if (HasBit(free_names, M(STR_SV_STNAME))) return STR_SV_STNAME;
00311
00312 if (HasBit(free_names, M(STR_SV_STNAME_CENTRAL))) return STR_SV_STNAME_CENTRAL;
00313 }
00314
00315
00316 if (HasBit(free_names, M(STR_SV_STNAME_LAKESIDE)) &&
00317 DistanceFromEdge(tile) < 20 &&
00318 CountMapSquareAround(tile, CMSAWater) >= 5) {
00319 return STR_SV_STNAME_LAKESIDE;
00320 }
00321
00322
00323 if (HasBit(free_names, M(STR_SV_STNAME_WOODS)) && (
00324 CountMapSquareAround(tile, CMSATree) >= 8 ||
00325 CountMapSquareAround(tile, CMSAForest) >= 2)
00326 ) {
00327 return _settings_game.game_creation.landscape == LT_TROPIC ? STR_SV_STNAME_FOREST : STR_SV_STNAME_WOODS;
00328 }
00329
00330
00331 uint z = GetTileZ(tile);
00332 uint z2 = GetTileZ(t->xy);
00333 if (z < z2) {
00334 if (HasBit(free_names, M(STR_SV_STNAME_VALLEY))) return STR_SV_STNAME_VALLEY;
00335 } else if (z > z2) {
00336 if (HasBit(free_names, M(STR_SV_STNAME_HEIGHTS))) return STR_SV_STNAME_HEIGHTS;
00337 }
00338
00339
00340 static const int8 _direction_and_table[] = {
00341 ~( (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
00342 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
00343 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
00344 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) ),
00345 };
00346
00347 free_names &= _direction_and_table[
00348 (TileX(tile) < TileX(t->xy)) +
00349 (TileY(tile) < TileY(t->xy)) * 2];
00350
00351 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));
00352 return (tmp == 0) ? STR_SV_STNAME_FALLBACK : (STR_SV_STNAME + FindFirstBit(tmp));
00353 }
00354 #undef M
00355
00361 static Station *GetClosestDeletedStation(TileIndex tile)
00362 {
00363 uint threshold = 8;
00364 Station *best_station = NULL;
00365 Station *st;
00366
00367 FOR_ALL_STATIONS(st) {
00368 if (!st->IsInUse() && st->owner == _current_company) {
00369 uint cur_dist = DistanceManhattan(tile, st->xy);
00370
00371 if (cur_dist < threshold) {
00372 threshold = cur_dist;
00373 best_station = st;
00374 }
00375 }
00376 }
00377
00378 return best_station;
00379 }
00380
00381
00382 void Station::GetTileArea(TileArea *ta, StationType type) const
00383 {
00384 switch (type) {
00385 case STATION_RAIL:
00386 *ta = this->train_station;
00387 return;
00388
00389 case STATION_AIRPORT:
00390 *ta = this->airport;
00391 return;
00392
00393 case STATION_TRUCK:
00394 *ta = this->truck_station;
00395 return;
00396
00397 case STATION_BUS:
00398 *ta = this->bus_station;
00399 return;
00400
00401 case STATION_DOCK:
00402 case STATION_OILRIG:
00403 ta->tile = this->dock_tile;
00404 break;
00405
00406 default: NOT_REACHED();
00407 }
00408
00409 ta->w = 1;
00410 ta->h = 1;
00411 }
00412
00416 void Station::UpdateVirtCoord()
00417 {
00418 Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
00419
00420 pt.y -= 32;
00421 if ((this->facilities & FACIL_AIRPORT) && this->airport.type == AT_OILRIG) pt.y -= 16;
00422
00423 SetDParam(0, this->index);
00424 SetDParam(1, this->facilities);
00425 this->sign.UpdatePosition(pt.x, pt.y, STR_VIEWPORT_STATION);
00426
00427 SetWindowDirty(WC_STATION_VIEW, this->index);
00428 }
00429
00431 void UpdateAllStationVirtCoords()
00432 {
00433 BaseStation *st;
00434
00435 FOR_ALL_BASE_STATIONS(st) {
00436 st->UpdateVirtCoord();
00437 }
00438 }
00439
00445 static uint GetAcceptanceMask(const Station *st)
00446 {
00447 uint mask = 0;
00448
00449 for (CargoID i = 0; i < NUM_CARGO; i++) {
00450 if (HasBit(st->goods[i].acceptance_pickup, GoodsEntry::ACCEPTANCE)) mask |= 1 << i;
00451 }
00452 return mask;
00453 }
00454
00459 static void ShowRejectOrAcceptNews(const Station *st, uint num_items, CargoID *cargo, StringID msg)
00460 {
00461 for (uint i = 0; i < num_items; i++) {
00462 SetDParam(i + 1, CargoSpec::Get(cargo[i])->name);
00463 }
00464
00465 SetDParam(0, st->index);
00466 AddNewsItem(msg, NS_ACCEPTANCE, NR_STATION, st->index);
00467 }
00468
00476 CargoArray GetProductionAroundTiles(TileIndex tile, int w, int h, int rad)
00477 {
00478 CargoArray produced;
00479
00480 int x = TileX(tile);
00481 int y = TileY(tile);
00482
00483
00484
00485 int x2 = min(x + w + rad, MapSizeX());
00486 int x1 = max(x - rad, 0);
00487
00488 int y2 = min(y + h + rad, MapSizeY());
00489 int y1 = max(y - rad, 0);
00490
00491 assert(x1 < x2);
00492 assert(y1 < y2);
00493 assert(w > 0);
00494 assert(h > 0);
00495
00496 TileArea ta(TileXY(x1, y1), TileXY(x2 - 1, y2 - 1));
00497
00498
00499
00500 TILE_AREA_LOOP(tile, ta) AddProducedCargo(tile, produced);
00501
00502
00503
00504
00505
00506
00507
00508 const Industry *i;
00509 FOR_ALL_INDUSTRIES(i) {
00510 if (!ta.Intersects(i->location)) continue;
00511
00512 for (uint j = 0; j < lengthof(i->produced_cargo); j++) {
00513 CargoID cargo = i->produced_cargo[j];
00514 if (cargo != CT_INVALID) produced[cargo]++;
00515 }
00516 }
00517
00518 return produced;
00519 }
00520
00529 CargoArray GetAcceptanceAroundTiles(TileIndex tile, int w, int h, int rad, uint32 *always_accepted)
00530 {
00531 CargoArray acceptance;
00532 if (always_accepted != NULL) *always_accepted = 0;
00533
00534 int x = TileX(tile);
00535 int y = TileY(tile);
00536
00537
00538
00539 int x2 = min(x + w + rad, MapSizeX());
00540 int y2 = min(y + h + rad, MapSizeY());
00541 int x1 = max(x - rad, 0);
00542 int y1 = max(y - rad, 0);
00543
00544 assert(x1 < x2);
00545 assert(y1 < y2);
00546 assert(w > 0);
00547 assert(h > 0);
00548
00549 for (int yc = y1; yc != y2; yc++) {
00550 for (int xc = x1; xc != x2; xc++) {
00551 TileIndex tile = TileXY(xc, yc);
00552 AddAcceptedCargo(tile, acceptance, always_accepted);
00553 }
00554 }
00555
00556 return acceptance;
00557 }
00558
00564 void UpdateStationAcceptance(Station *st, bool show_msg)
00565 {
00566
00567 uint old_acc = GetAcceptanceMask(st);
00568
00569
00570 CargoArray acceptance;
00571 if (!st->rect.IsEmpty()) {
00572 acceptance = GetAcceptanceAroundTiles(
00573 TileXY(st->rect.left, st->rect.top),
00574 st->rect.right - st->rect.left + 1,
00575 st->rect.bottom - st->rect.top + 1,
00576 st->GetCatchmentRadius(),
00577 &st->always_accepted
00578 );
00579 }
00580
00581
00582 for (CargoID i = 0; i < NUM_CARGO; i++) {
00583 uint amt = min(acceptance[i], 15);
00584
00585
00586 bool is_passengers = IsCargoInClass(i, CC_PASSENGERS);
00587 if ((!is_passengers && !(st->facilities & ~FACIL_BUS_STOP)) ||
00588 (is_passengers && !(st->facilities & ~FACIL_TRUCK_STOP))) {
00589 amt = 0;
00590 }
00591
00592 SB(st->goods[i].acceptance_pickup, GoodsEntry::ACCEPTANCE, 1, amt >= 8);
00593 }
00594
00595
00596 uint new_acc = GetAcceptanceMask(st);
00597 if (old_acc == new_acc) return;
00598
00599
00600 if (show_msg && st->owner == _local_company && st->IsInUse()) {
00601
00602
00603 static const StringID accept_msg[] = {
00604 STR_NEWS_STATION_NOW_ACCEPTS_CARGO,
00605 STR_NEWS_STATION_NOW_ACCEPTS_CARGO_AND_CARGO,
00606 };
00607 static const StringID reject_msg[] = {
00608 STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO,
00609 STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO_OR_CARGO,
00610 };
00611
00612
00613 CargoID accepts[2] = { CT_INVALID, CT_INVALID };
00614 CargoID rejects[2] = { CT_INVALID, CT_INVALID };
00615 uint num_acc = 0;
00616 uint num_rej = 0;
00617
00618
00619 for (CargoID i = 0; i < NUM_CARGO; i++) {
00620 if (HasBit(new_acc, i)) {
00621 if (!HasBit(old_acc, i) && num_acc < lengthof(accepts)) {
00622
00623 accepts[num_acc++] = i;
00624 }
00625 } else {
00626 if (HasBit(old_acc, i) && num_rej < lengthof(rejects)) {
00627
00628 rejects[num_rej++] = i;
00629 }
00630 }
00631 }
00632
00633
00634 if (num_acc > 0) ShowRejectOrAcceptNews(st, num_acc, accepts, accept_msg[num_acc - 1]);
00635 if (num_rej > 0) ShowRejectOrAcceptNews(st, num_rej, rejects, reject_msg[num_rej - 1]);
00636 }
00637
00638
00639 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_ACCEPTLIST);
00640 }
00641
00642 static void UpdateStationSignCoord(BaseStation *st)
00643 {
00644 const StationRect *r = &st->rect;
00645
00646 if (r->IsEmpty()) return;
00647
00648
00649 st->xy = TileXY(ClampU(TileX(st->xy), r->left, r->right), ClampU(TileY(st->xy), r->top, r->bottom));
00650 st->UpdateVirtCoord();
00651 }
00652
00659 static void DeleteStationIfEmpty(BaseStation *st)
00660 {
00661 if (!st->IsInUse()) {
00662 st->delete_ctr = 0;
00663 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
00664 }
00665
00666 UpdateStationSignCoord(st);
00667 }
00668
00669 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags);
00670
00679 CommandCost CheckBuildableTile(TileIndex tile, uint invalid_dirs, int &allowed_z, bool check_bridge = true)
00680 {
00681 if (check_bridge && MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) {
00682 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00683 }
00684
00685 CommandCost ret = EnsureNoVehicleOnGround(tile);
00686 if (ret.Failed()) return ret;
00687
00688 uint z;
00689 Slope tileh = GetTileSlope(tile, &z);
00690
00691
00692
00693
00694
00695 if (IsSteepSlope(tileh) ||
00696 ((!_settings_game.construction.build_on_slopes) && tileh != SLOPE_FLAT)) {
00697 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00698 }
00699
00700 CommandCost cost(EXPENSES_CONSTRUCTION);
00701 int flat_z = z;
00702 if (tileh != SLOPE_FLAT) {
00703
00704 if ((HasBit(invalid_dirs, DIAGDIR_NE) && !(tileh & SLOPE_NE)) ||
00705 (HasBit(invalid_dirs, DIAGDIR_SE) && !(tileh & SLOPE_SE)) ||
00706 (HasBit(invalid_dirs, DIAGDIR_SW) && !(tileh & SLOPE_SW)) ||
00707 (HasBit(invalid_dirs, DIAGDIR_NW) && !(tileh & SLOPE_NW))) {
00708 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00709 }
00710 cost.AddCost(_price[PR_BUILD_FOUNDATION]);
00711 flat_z += TILE_HEIGHT;
00712 }
00713
00714
00715 if (allowed_z < 0) {
00716
00717 allowed_z = flat_z;
00718 } else if (allowed_z != flat_z) {
00719 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00720 }
00721
00722 return cost;
00723 }
00724
00731 CommandCost CheckFlatLand(TileArea tile_area, DoCommandFlag flags)
00732 {
00733 CommandCost cost(EXPENSES_CONSTRUCTION);
00734 int allowed_z = -1;
00735
00736 TILE_AREA_LOOP(tile_cur, tile_area) {
00737 CommandCost ret = CheckBuildableTile(tile_cur, 0, allowed_z);
00738 if (ret.Failed()) return ret;
00739 cost.AddCost(ret);
00740
00741 ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00742 if (ret.Failed()) return ret;
00743 cost.AddCost(ret);
00744 }
00745
00746 return cost;
00747 }
00748
00759 static CommandCost CheckFlatLandRailStation(TileArea tile_area, DoCommandFlag flags, uint invalid_dirs, StationID *station, RailType rt, SmallVector<Train *, 4> &affected_vehicles)
00760 {
00761 CommandCost cost(EXPENSES_CONSTRUCTION);
00762 int allowed_z = -1;
00763
00764 TILE_AREA_LOOP(tile_cur, tile_area) {
00765 CommandCost ret = CheckBuildableTile(tile_cur, invalid_dirs, allowed_z);
00766 if (ret.Failed()) return ret;
00767 cost.AddCost(ret);
00768
00769
00770
00771
00772 if (station != NULL && IsTileType(tile_cur, MP_STATION)) {
00773 if (!IsRailStation(tile_cur)) {
00774 return ClearTile_Station(tile_cur, DC_AUTO);
00775 } else {
00776 StationID st = GetStationIndex(tile_cur);
00777 if (*station == INVALID_STATION) {
00778 *station = st;
00779 } else if (*station != st) {
00780 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
00781 }
00782 }
00783 } else {
00784
00785
00786 if (rt != INVALID_RAILTYPE &&
00787 IsPlainRailTile(tile_cur) && !HasSignals(tile_cur) &&
00788 HasPowerOnRail(GetRailType(tile_cur), rt)) {
00789
00790
00791
00792
00793
00794
00795 TrackBits tracks = GetTrackBits(tile_cur);
00796 Track track = RemoveFirstTrack(&tracks);
00797 Track expected_track = HasBit(invalid_dirs, DIAGDIR_NE) ? TRACK_X : TRACK_Y;
00798
00799 if (tracks == TRACK_BIT_NONE && track == expected_track) {
00800
00801 if (HasBit(GetRailReservationTrackBits(tile_cur), track)) {
00802 Train *v = GetTrainForReservation(tile_cur, track);
00803 if (v != NULL) {
00804 *affected_vehicles.Append() = v;
00805 }
00806 }
00807 CommandCost ret = DoCommand(tile_cur, 0, track, flags, CMD_REMOVE_SINGLE_RAIL);
00808 if (ret.Failed()) return ret;
00809 cost.AddCost(ret);
00810
00811 continue;
00812 }
00813 }
00814 ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00815 if (ret.Failed()) return ret;
00816 cost.AddCost(ret);
00817 }
00818 }
00819
00820 return cost;
00821 }
00822
00835 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)
00836 {
00837 CommandCost cost(EXPENSES_CONSTRUCTION);
00838 int allowed_z = -1;
00839
00840 TILE_AREA_LOOP(cur_tile, tile_area) {
00841 CommandCost ret = CheckBuildableTile(cur_tile, invalid_dirs, allowed_z);
00842 if (ret.Failed()) return ret;
00843 cost.AddCost(ret);
00844
00845
00846
00847
00848 if (station != NULL && IsTileType(cur_tile, MP_STATION)) {
00849 if (!IsRoadStop(cur_tile)) {
00850 return ClearTile_Station(cur_tile, DC_AUTO);
00851 } else {
00852 if (is_truck_stop != IsTruckStop(cur_tile) ||
00853 is_drive_through != IsDriveThroughStopTile(cur_tile)) {
00854 return ClearTile_Station(cur_tile, DC_AUTO);
00855 }
00856
00857 if (is_drive_through && IsDriveThroughStopTile(cur_tile) && DiagDirToAxis(GetRoadStopDir(cur_tile)) != axis){
00858 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
00859 }
00860 StationID st = GetStationIndex(cur_tile);
00861 if (*station == INVALID_STATION) {
00862 *station = st;
00863 } else if (*station != st) {
00864 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
00865 }
00866 }
00867 } else {
00868 bool build_over_road = is_drive_through && IsNormalRoadTile(cur_tile);
00869
00870 RoadBits rb = IsNormalRoadTile(cur_tile) ? GetAllRoadBits(cur_tile) : ROAD_NONE;
00871 if (build_over_road && (rb & (axis == AXIS_X ? ROAD_Y : ROAD_X)) != 0) {
00872
00873 switch (CountBits(rb)) {
00874 case 1:
00875 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
00876
00877 case 2:
00878 if (rb == ROAD_X || rb == ROAD_Y) return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
00879 return_cmd_error(STR_ERROR_DRIVE_THROUGH_CORNER);
00880
00881 default:
00882 return_cmd_error(STR_ERROR_DRIVE_THROUGH_JUNCTION);
00883 }
00884 }
00885
00886 RoadTypes cur_rts = IsNormalRoadTile(cur_tile) ? GetRoadTypes(cur_tile) : ROADTYPES_NONE;
00887 uint num_roadbits = 0;
00888 if (build_over_road) {
00889
00890 if (HasBit(cur_rts, ROADTYPE_ROAD)) {
00891 Owner road_owner = GetRoadOwner(cur_tile, ROADTYPE_ROAD);
00892 if (road_owner == OWNER_TOWN) {
00893 if (!_settings_game.construction.road_stop_on_town_road) return_cmd_error(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD);
00894 } else if (!_settings_game.construction.road_stop_on_competitor_road && road_owner != OWNER_NONE) {
00895 CommandCost ret = CheckOwnership(road_owner);
00896 if (ret.Failed()) return ret;
00897 }
00898 num_roadbits += CountBits(GetRoadBits(cur_tile, ROADTYPE_ROAD));
00899 }
00900
00901
00902 if (HasBit(cur_rts, ROADTYPE_TRAM)) {
00903 Owner tram_owner = GetRoadOwner(cur_tile, ROADTYPE_TRAM);
00904 if (!_settings_game.construction.road_stop_on_competitor_road && tram_owner != OWNER_NONE) {
00905 CommandCost ret = CheckOwnership(tram_owner);
00906 if (ret.Failed()) return ret;
00907 }
00908 num_roadbits += CountBits(GetRoadBits(cur_tile, ROADTYPE_TRAM));
00909 }
00910
00911
00912 rts |= cur_rts;
00913 } else {
00914 ret = DoCommand(cur_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00915 if (ret.Failed()) return ret;
00916 cost.AddCost(ret);
00917 }
00918
00919 uint roadbits_to_build = CountBits(rts) * 2 - num_roadbits;
00920 cost.AddCost(_price[PR_BUILD_ROAD] * roadbits_to_build);
00921 }
00922 }
00923
00924 return cost;
00925 }
00926
00934 CommandCost CanExpandRailStation(const BaseStation *st, TileArea &new_ta, Axis axis)
00935 {
00936 TileArea cur_ta = st->train_station;
00937
00938
00939 int x = min(TileX(cur_ta.tile), TileX(new_ta.tile));
00940 int y = min(TileY(cur_ta.tile), TileY(new_ta.tile));
00941 new_ta.w = max(TileX(cur_ta.tile) + cur_ta.w, TileX(new_ta.tile) + new_ta.w) - x;
00942 new_ta.h = max(TileY(cur_ta.tile) + cur_ta.h, TileY(new_ta.tile) + new_ta.h) - y;
00943 new_ta.tile = TileXY(x, y);
00944
00945
00946 if (new_ta.w > _settings_game.station.station_spread || new_ta.h > _settings_game.station.station_spread) {
00947 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
00948 }
00949
00950 return CommandCost();
00951 }
00952
00953 static inline byte *CreateSingle(byte *layout, int n)
00954 {
00955 int i = n;
00956 do *layout++ = 0; while (--i);
00957 layout[((n - 1) >> 1) - n] = 2;
00958 return layout;
00959 }
00960
00961 static inline byte *CreateMulti(byte *layout, int n, byte b)
00962 {
00963 int i = n;
00964 do *layout++ = b; while (--i);
00965 if (n > 4) {
00966 layout[0 - n] = 0;
00967 layout[n - 1 - n] = 0;
00968 }
00969 return layout;
00970 }
00971
00979 void GetStationLayout(byte *layout, int numtracks, int plat_len, const StationSpec *statspec)
00980 {
00981 if (statspec != NULL && statspec->lengths >= plat_len &&
00982 statspec->platforms[plat_len - 1] >= numtracks &&
00983 statspec->layouts[plat_len - 1][numtracks - 1]) {
00984
00985 memcpy(layout, statspec->layouts[plat_len - 1][numtracks - 1],
00986 plat_len * numtracks);
00987 return;
00988 }
00989
00990 if (plat_len == 1) {
00991 CreateSingle(layout, numtracks);
00992 } else {
00993 if (numtracks & 1) layout = CreateSingle(layout, plat_len);
00994 numtracks >>= 1;
00995
00996 while (--numtracks >= 0) {
00997 layout = CreateMulti(layout, plat_len, 4);
00998 layout = CreateMulti(layout, plat_len, 6);
00999 }
01000 }
01001 }
01002
01014 template <class T, StringID error_message>
01015 CommandCost FindJoiningBaseStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, T **st)
01016 {
01017 assert(*st == NULL);
01018 bool check_surrounding = true;
01019
01020 if (_settings_game.station.adjacent_stations) {
01021 if (existing_station != INVALID_STATION) {
01022 if (adjacent && existing_station != station_to_join) {
01023
01024
01025 return_cmd_error(error_message);
01026 } else {
01027
01028
01029 *st = T::GetIfValid(existing_station);
01030 check_surrounding = (*st == NULL);
01031 }
01032 } else {
01033
01034
01035 if (adjacent) check_surrounding = false;
01036 }
01037 }
01038
01039 if (check_surrounding) {
01040
01041 CommandCost ret = GetStationAround(ta, existing_station, st);
01042 if (ret.Failed()) return ret;
01043 }
01044
01045
01046 if (*st == NULL && station_to_join != INVALID_STATION) *st = T::GetIfValid(station_to_join);
01047
01048 return CommandCost();
01049 }
01050
01060 static CommandCost FindJoiningStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
01061 {
01062 return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_RAILWAY_STATION_FIRST>(existing_station, station_to_join, adjacent, ta, st);
01063 }
01064
01074 CommandCost FindJoiningWaypoint(StationID existing_waypoint, StationID waypoint_to_join, bool adjacent, TileArea ta, Waypoint **wp)
01075 {
01076 return FindJoiningBaseStation<Waypoint, STR_ERROR_MUST_REMOVE_RAILWAYPOINT_FIRST>(existing_waypoint, waypoint_to_join, adjacent, ta, wp);
01077 }
01078
01096 CommandCost CmdBuildRailStation(TileIndex tile_org, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01097 {
01098
01099 RailType rt = Extract<RailType, 0, 4>(p1);
01100 Axis axis = Extract<Axis, 4, 1>(p1);
01101 byte numtracks = GB(p1, 8, 8);
01102 byte plat_len = GB(p1, 16, 8);
01103 bool adjacent = HasBit(p1, 24);
01104
01105 StationClassID spec_class = Extract<StationClassID, 0, 8>(p2);
01106 byte spec_index = GB(p2, 8, 8);
01107 StationID station_to_join = GB(p2, 16, 16);
01108
01109
01110 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile_org, flags);
01111 if (ret.Failed()) return ret;
01112
01113 if (!ValParamRailtype(rt)) return CMD_ERROR;
01114
01115
01116 if ((uint)spec_class >= StationClass::GetCount() || spec_class == STAT_CLASS_WAYP) return CMD_ERROR;
01117 if (spec_index >= StationClass::GetCount(spec_class)) return CMD_ERROR;
01118 if (plat_len == 0 || numtracks == 0) return CMD_ERROR;
01119
01120 int w_org, h_org;
01121 if (axis == AXIS_X) {
01122 w_org = plat_len;
01123 h_org = numtracks;
01124 } else {
01125 h_org = plat_len;
01126 w_org = numtracks;
01127 }
01128
01129 bool reuse = (station_to_join != NEW_STATION);
01130 if (!reuse) station_to_join = INVALID_STATION;
01131 bool distant_join = (station_to_join != INVALID_STATION);
01132
01133 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
01134
01135 if (h_org > _settings_game.station.station_spread || w_org > _settings_game.station.station_spread) return CMD_ERROR;
01136
01137
01138 TileArea new_location(tile_org, w_org, h_org);
01139
01140
01141 StationID est = INVALID_STATION;
01142 SmallVector<Train *, 4> affected_vehicles;
01143
01144 CommandCost cost = CheckFlatLandRailStation(TileArea(tile_org, w_org, h_org), flags, 5 << axis, &est, rt, affected_vehicles);
01145 if (cost.Failed()) return cost;
01146
01147 cost.AddCost((numtracks * _price[PR_BUILD_STATION_RAIL] + _price[PR_BUILD_STATION_RAIL_LENGTH]) * plat_len);
01148 cost.AddCost(numtracks * plat_len * RailBuildCost(rt));
01149
01150 Station *st = NULL;
01151 ret = FindJoiningStation(est, station_to_join, adjacent, new_location, &st);
01152 if (ret.Failed()) return ret;
01153
01154
01155 if (st == NULL && reuse) st = GetClosestDeletedStation(tile_org);
01156
01157 if (st != NULL) {
01158
01159 if (st->owner != _current_company) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
01160
01161 if (st->train_station.tile != INVALID_TILE) {
01162 CommandCost ret = CanExpandRailStation(st, new_location, axis);
01163 if (ret.Failed()) return ret;
01164 }
01165
01166
01167 CommandCost ret = st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TEST);
01168 if (ret.Failed()) return ret;
01169 } else {
01170
01171 if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
01172
01173 if (flags & DC_EXEC) {
01174 st = new Station(tile_org);
01175
01176 st->town = ClosestTownFromTile(tile_org, UINT_MAX);
01177 st->string_id = GenerateStationName(st, tile_org, STATIONNAMING_RAIL);
01178
01179 if (Company::IsValidID(_current_company)) {
01180 SetBit(st->town->have_ratings, _current_company);
01181 }
01182 }
01183 }
01184
01185
01186 const StationSpec *statspec = StationClass::Get(spec_class, spec_index);
01187 int specindex = AllocateSpecToStation(statspec, st, (flags & DC_EXEC) != 0);
01188 if (specindex == -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS);
01189
01190 if (statspec != NULL) {
01191
01192
01193
01194 if (HasBit(statspec->disallowed_platforms, numtracks - 1) || HasBit(statspec->disallowed_lengths, plat_len - 1)) {
01195 return CMD_ERROR;
01196 }
01197
01198
01199 if (HasBit(statspec->callback_mask, CBM_STATION_AVAIL) && GB(GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, NULL, INVALID_TILE), 0, 8) == 0) {
01200 return CMD_ERROR;
01201 }
01202 }
01203
01204 if (flags & DC_EXEC) {
01205 TileIndexDiff tile_delta;
01206 byte *layout_ptr;
01207 byte numtracks_orig;
01208 Track track;
01209
01210 st->train_station = new_location;
01211 st->AddFacility(FACIL_TRAIN, new_location.tile);
01212
01213 st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TRY);
01214
01215 if (statspec != NULL) {
01216
01217
01218 st->cached_anim_triggers |= statspec->animation.triggers;
01219 }
01220
01221 tile_delta = (axis == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
01222 track = AxisToTrack(axis);
01223
01224 layout_ptr = AllocaM(byte, numtracks * plat_len);
01225 GetStationLayout(layout_ptr, numtracks, plat_len, statspec);
01226
01227 numtracks_orig = numtracks;
01228
01229 do {
01230 TileIndex tile = tile_org;
01231 int w = plat_len;
01232 do {
01233 byte layout = *layout_ptr++;
01234 if (IsRailStationTile(tile) && HasStationReservation(tile)) {
01235
01236 Train *v = GetTrainForReservation(tile, AxisToTrack(GetRailStationAxis(tile)));
01237 if (v != NULL) {
01238 FreeTrainTrackReservation(v);
01239 *affected_vehicles.Append() = v;
01240 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
01241 for (; v->Next() != NULL; v = v->Next()) { }
01242 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), false);
01243 }
01244 }
01245
01246
01247 DeleteAnimatedTile(tile);
01248 byte old_specindex = HasStationTileRail(tile) ? GetCustomStationSpecIndex(tile) : 0;
01249 MakeRailStation(tile, st->owner, st->index, axis, layout & ~1, rt);
01250
01251 DeallocateSpecFromStation(st, old_specindex);
01252
01253 SetCustomStationSpecIndex(tile, specindex);
01254 SetStationTileRandomBits(tile, GB(Random(), 0, 4));
01255 SetAnimationFrame(tile, 0);
01256
01257 if (statspec != NULL) {
01258
01259 uint32 platinfo = GetPlatformInfo(AXIS_X, 0, plat_len, numtracks_orig, plat_len - w, numtracks_orig - numtracks, false);
01260
01261
01262 uint16 callback = GetStationCallback(CBID_STATION_TILE_LAYOUT, platinfo, 0, statspec, NULL, tile);
01263 if (callback != CALLBACK_FAILED && callback < 8) SetStationGfx(tile, (callback & ~1) + axis);
01264
01265
01266 TriggerStationAnimation(st, tile, SAT_BUILT);
01267 }
01268
01269 tile += tile_delta;
01270 } while (--w);
01271 AddTrackToSignalBuffer(tile_org, track, _current_company);
01272 YapfNotifyTrackLayoutChange(tile_org, track);
01273 tile_org += tile_delta ^ TileDiffXY(1, 1);
01274 } while (--numtracks);
01275
01276 for (uint i = 0; i < affected_vehicles.Length(); ++i) {
01277
01278 Train *v = affected_vehicles[i];
01279 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
01280 TryPathReserve(v, true, true);
01281 for (; v->Next() != NULL; v = v->Next()) { }
01282 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
01283 }
01284
01285 st->MarkTilesDirty(false);
01286 st->UpdateVirtCoord();
01287 UpdateStationAcceptance(st, false);
01288 st->RecomputeIndustriesNear();
01289 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
01290 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
01291 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_TRAINS);
01292 }
01293
01294 return cost;
01295 }
01296
01297 static void MakeRailStationAreaSmaller(BaseStation *st)
01298 {
01299 TileArea ta = st->train_station;
01300
01301 restart:
01302
01303
01304 if (ta.w != 0 && ta.h != 0) {
01305
01306 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(0, i));) {
01307
01308 if (++i == ta.h) {
01309 ta.tile += TileDiffXY(1, 0);
01310 ta.w--;
01311 goto restart;
01312 }
01313 }
01314
01315
01316 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(ta.w - 1, i));) {
01317
01318 if (++i == ta.h) {
01319 ta.w--;
01320 goto restart;
01321 }
01322 }
01323
01324
01325 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(i, 0));) {
01326
01327 if (++i == ta.w) {
01328 ta.tile += TileDiffXY(0, 1);
01329 ta.h--;
01330 goto restart;
01331 }
01332 }
01333
01334
01335 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(i, ta.h - 1));) {
01336
01337 if (++i == ta.w) {
01338 ta.h--;
01339 goto restart;
01340 }
01341 }
01342 } else {
01343 ta.Clear();
01344 }
01345
01346 st->train_station = ta;
01347 }
01348
01359 template <class T>
01360 CommandCost RemoveFromRailBaseStation(TileArea ta, SmallVector<T *, 4> &affected_stations, DoCommandFlag flags, Money removal_cost, bool keep_rail)
01361 {
01362
01363 int quantity = 0;
01364 CommandCost total_cost(EXPENSES_CONSTRUCTION);
01365
01366
01367 TILE_AREA_LOOP(tile, ta) {
01368
01369 if (!HasStationTileRail(tile)) continue;
01370
01371
01372 CommandCost ret = EnsureNoVehicleOnGround(tile);
01373 if (ret.Failed()) continue;
01374
01375
01376 T *st = T::GetByTile(tile);
01377 if (st == NULL) continue;
01378
01379 if (_current_company != OWNER_WATER) {
01380 CommandCost ret = CheckOwnership(st->owner);
01381 if (ret.Failed()) continue;
01382 }
01383
01384
01385 quantity++;
01386
01387 if (keep_rail || IsStationTileBlocked(tile)) {
01388
01389
01390 total_cost.AddCost(-_price[PR_CLEAR_RAIL]);
01391 }
01392
01393 if (flags & DC_EXEC) {
01394
01395 uint specindex = GetCustomStationSpecIndex(tile);
01396 Track track = GetRailStationTrack(tile);
01397 Owner owner = GetTileOwner(tile);
01398 RailType rt = GetRailType(tile);
01399 Train *v = NULL;
01400
01401 if (HasStationReservation(tile)) {
01402 v = GetTrainForReservation(tile, track);
01403 if (v != NULL) {
01404
01405 FreeTrainTrackReservation(v);
01406 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
01407 Vehicle *temp = v;
01408 for (; temp->Next() != NULL; temp = temp->Next()) { }
01409 if (IsRailStationTile(temp->tile)) SetRailStationPlatformReservation(temp->tile, TrackdirToExitdir(ReverseTrackdir(temp->GetVehicleTrackdir())), false);
01410 }
01411 }
01412
01413 bool build_rail = keep_rail && !IsStationTileBlocked(tile);
01414
01415 DoClearSquare(tile);
01416 DeleteNewGRFInspectWindow(GSF_STATIONS, tile);
01417 if (build_rail) MakeRailNormal(tile, owner, TrackToTrackBits(track), rt);
01418
01419 st->rect.AfterRemoveTile(st, tile);
01420 AddTrackToSignalBuffer(tile, track, owner);
01421 YapfNotifyTrackLayoutChange(tile, track);
01422
01423 DeallocateSpecFromStation(st, specindex);
01424
01425 affected_stations.Include(st);
01426
01427 if (v != NULL) {
01428
01429 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
01430 TryPathReserve(v, true, true);
01431 for (; v->Next() != NULL; v = v->Next()) { }
01432 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
01433 }
01434 }
01435 }
01436
01437 if (quantity == 0) return_cmd_error(STR_ERROR_THERE_IS_NO_STATION);
01438
01439 for (T **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
01440 T *st = *stp;
01441
01442
01443
01444
01445 MakeRailStationAreaSmaller(st);
01446 UpdateStationSignCoord(st);
01447
01448
01449 if (st->train_station.tile == INVALID_TILE) {
01450 st->facilities &= ~FACIL_TRAIN;
01451 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_TRAINS);
01452 st->UpdateVirtCoord();
01453 DeleteStationIfEmpty(st);
01454 }
01455 }
01456
01457 total_cost.AddCost(quantity * removal_cost);
01458 return total_cost;
01459 }
01460
01472 CommandCost CmdRemoveFromRailStation(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01473 {
01474 TileIndex end = p1 == 0 ? start : p1;
01475 if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
01476
01477 TileArea ta(start, end);
01478 SmallVector<Station *, 4> affected_stations;
01479
01480 CommandCost ret = RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_STATION_RAIL], HasBit(p2, 0));
01481 if (ret.Failed()) return ret;
01482
01483
01484 for (Station **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
01485 Station *st = *stp;
01486
01487 if (st->train_station.tile == INVALID_TILE) SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_TRAINS);
01488 st->MarkTilesDirty(false);
01489 st->RecomputeIndustriesNear();
01490 }
01491
01492
01493 return ret;
01494 }
01495
01507 CommandCost CmdRemoveFromRailWaypoint(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01508 {
01509 TileIndex end = p1 == 0 ? start : p1;
01510 if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
01511
01512 TileArea ta(start, end);
01513 SmallVector<Waypoint *, 4> affected_stations;
01514
01515 return RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_WAYPOINT_RAIL], HasBit(p2, 0));
01516 }
01517
01518
01526 template <class T>
01527 CommandCost RemoveRailStation(T *st, DoCommandFlag flags)
01528 {
01529
01530 if (_current_company != OWNER_WATER) {
01531 CommandCost ret = CheckOwnership(st->owner);
01532 if (ret.Failed()) return ret;
01533 }
01534
01535
01536 TileArea ta = st->train_station;
01537
01538 assert(ta.w != 0 && ta.h != 0);
01539
01540 CommandCost cost(EXPENSES_CONSTRUCTION);
01541
01542 TILE_AREA_LOOP(tile, ta) {
01543
01544 if (!st->TileBelongsToRailStation(tile)) continue;
01545
01546 CommandCost ret = EnsureNoVehicleOnGround(tile);
01547 if (ret.Failed()) return ret;
01548
01549 cost.AddCost(_price[PR_CLEAR_STATION_RAIL]);
01550 if (flags & DC_EXEC) {
01551
01552 Track track = GetRailStationTrack(tile);
01553 Owner owner = GetTileOwner(tile);
01554 Train *v = NULL;
01555 if (HasStationReservation(tile)) {
01556 v = GetTrainForReservation(tile, track);
01557 if (v != NULL) FreeTrainTrackReservation(v);
01558 }
01559 DoClearSquare(tile);
01560 DeleteNewGRFInspectWindow(GSF_STATIONS, tile);
01561 AddTrackToSignalBuffer(tile, track, owner);
01562 YapfNotifyTrackLayoutChange(tile, track);
01563 if (v != NULL) TryPathReserve(v, true);
01564 }
01565 }
01566
01567 if (flags & DC_EXEC) {
01568 st->rect.AfterRemoveRect(st, st->train_station);
01569
01570 st->train_station.Clear();
01571
01572 st->facilities &= ~FACIL_TRAIN;
01573
01574 free(st->speclist);
01575 st->num_specs = 0;
01576 st->speclist = NULL;
01577 st->cached_anim_triggers = 0;
01578
01579 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_TRAINS);
01580 st->UpdateVirtCoord();
01581 DeleteStationIfEmpty(st);
01582 }
01583
01584 return cost;
01585 }
01586
01593 static CommandCost RemoveRailStation(TileIndex tile, DoCommandFlag flags)
01594 {
01595
01596 if (_current_company == OWNER_WATER) {
01597 return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_STATION);
01598 }
01599
01600 Station *st = Station::GetByTile(tile);
01601 CommandCost cost = RemoveRailStation(st, flags);
01602
01603 if (flags & DC_EXEC) st->RecomputeIndustriesNear();
01604
01605 return cost;
01606 }
01607
01614 static CommandCost RemoveRailWaypoint(TileIndex tile, DoCommandFlag flags)
01615 {
01616
01617 if (_current_company == OWNER_WATER) {
01618 return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_WAYPOINT);
01619 }
01620
01621 return RemoveRailStation(Waypoint::GetByTile(tile), flags);
01622 }
01623
01624
01630 static RoadStop **FindRoadStopSpot(bool truck_station, Station *st)
01631 {
01632 RoadStop **primary_stop = (truck_station) ? &st->truck_stops : &st->bus_stops;
01633
01634 if (*primary_stop == NULL) {
01635
01636 return primary_stop;
01637 } else {
01638
01639 RoadStop *stop = *primary_stop;
01640 while (stop->next != NULL) stop = stop->next;
01641 return &stop->next;
01642 }
01643 }
01644
01645 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags);
01646
01656 static CommandCost FindJoiningRoadStop(StationID existing_stop, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
01657 {
01658 return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST>(existing_stop, station_to_join, adjacent, ta, st);
01659 }
01660
01676 CommandCost CmdBuildRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01677 {
01678 bool type = HasBit(p2, 0);
01679 bool is_drive_through = HasBit(p2, 1);
01680 RoadTypes rts = Extract<RoadTypes, 2, 2>(p2);
01681 StationID station_to_join = GB(p2, 16, 16);
01682 bool reuse = (station_to_join != NEW_STATION);
01683 if (!reuse) station_to_join = INVALID_STATION;
01684 bool distant_join = (station_to_join != INVALID_STATION);
01685
01686 uint8 width = (uint8)GB(p1, 0, 8);
01687 uint8 lenght = (uint8)GB(p1, 8, 8);
01688
01689
01690 if (width > _settings_game.station.station_spread || lenght > _settings_game.station.station_spread) return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
01691
01692 if (width == 0 || lenght == 0) return CMD_ERROR;
01693
01694 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, lenght - 1) == INVALID_TILE) return CMD_ERROR;
01695
01696 TileArea roadstop_area(tile, width, lenght);
01697
01698 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
01699
01700 if (!HasExactlyOneBit(rts) || !HasRoadTypesAvail(_current_company, rts)) return CMD_ERROR;
01701
01702
01703 if (!is_drive_through && HasBit(rts, ROADTYPE_TRAM)) return CMD_ERROR;
01704
01705 DiagDirection ddir = Extract<DiagDirection, 6, 2>(p2);
01706
01707
01708 if (!IsValidDiagDirection(ddir)) return CMD_ERROR;
01709
01710 if (is_drive_through && !IsValidAxis((Axis)ddir)) return CMD_ERROR;
01711
01712 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
01713 if (ret.Failed()) return ret;
01714
01715
01716 CommandCost cost(EXPENSES_CONSTRUCTION, roadstop_area.w * roadstop_area.h * _price[type ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS]);
01717 StationID est = INVALID_STATION;
01718 ret = CheckFlatLandRoadStop(roadstop_area, flags, is_drive_through ? 5 << ddir : 1 << ddir, is_drive_through, type, DiagDirToAxis(ddir), &est, rts);
01719 if (ret.Failed()) return ret;
01720 cost.AddCost(ret);
01721
01722 Station *st = NULL;
01723 ret = FindJoiningRoadStop(est, station_to_join, HasBit(p2, 5), roadstop_area, &st);
01724 if (ret.Failed()) return ret;
01725
01726
01727 if (st == NULL && reuse) st = GetClosestDeletedStation(tile);
01728
01729
01730 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);
01731
01732 if (st != NULL) {
01733 if (st->owner != _current_company) {
01734 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
01735 }
01736
01737 CommandCost ret = st->rect.BeforeAddRect(roadstop_area.tile, roadstop_area.w, roadstop_area.h, StationRect::ADD_TEST);
01738 if (ret.Failed()) return ret;
01739 } else {
01740
01741 if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
01742
01743 if (flags & DC_EXEC) {
01744 st = new Station(tile);
01745
01746 st->town = ClosestTownFromTile(tile, UINT_MAX);
01747 st->string_id = GenerateStationName(st, tile, STATIONNAMING_ROAD);
01748
01749 if (Company::IsValidID(_current_company)) {
01750 SetBit(st->town->have_ratings, _current_company);
01751 }
01752 }
01753 }
01754
01755 if (flags & DC_EXEC) {
01756
01757 TILE_AREA_LOOP(cur_tile, roadstop_area) {
01758 RoadTypes cur_rts = GetRoadTypes(cur_tile);
01759 Owner road_owner = HasBit(cur_rts, ROADTYPE_ROAD) ? GetRoadOwner(cur_tile, ROADTYPE_ROAD) : _current_company;
01760 Owner tram_owner = HasBit(cur_rts, ROADTYPE_TRAM) ? GetRoadOwner(cur_tile, ROADTYPE_TRAM) : _current_company;
01761
01762 if (IsTileType(cur_tile, MP_STATION) && IsRoadStop(cur_tile)) {
01763 RemoveRoadStop(cur_tile, flags);
01764 }
01765
01766 RoadStop *road_stop = new RoadStop(cur_tile);
01767
01768 RoadStop **currstop = FindRoadStopSpot(type, st);
01769 *currstop = road_stop;
01770
01771 if (type) {
01772 st->truck_station.Add(cur_tile);
01773 } else {
01774 st->bus_station.Add(cur_tile);
01775 }
01776
01777
01778 st->AddFacility((type) ? FACIL_TRUCK_STOP : FACIL_BUS_STOP, cur_tile);
01779
01780 st->rect.BeforeAddTile(cur_tile, StationRect::ADD_TRY);
01781
01782 RoadStopType rs_type = type ? ROADSTOP_TRUCK : ROADSTOP_BUS;
01783 if (is_drive_through) {
01784 MakeDriveThroughRoadStop(cur_tile, st->owner, road_owner, tram_owner, st->index, rs_type, rts | cur_rts, DiagDirToAxis(ddir));
01785 road_stop->MakeDriveThrough();
01786 } else {
01787 MakeRoadStop(cur_tile, st->owner, st->index, rs_type, rts, ddir);
01788 }
01789
01790 MarkTileDirtyByTile(cur_tile);
01791 }
01792 }
01793
01794 if (st != NULL) {
01795 st->UpdateVirtCoord();
01796 UpdateStationAcceptance(st, false);
01797 st->RecomputeIndustriesNear();
01798 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
01799 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
01800 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_ROADVEHS);
01801 }
01802 return cost;
01803 }
01804
01805
01806 static Vehicle *ClearRoadStopStatusEnum(Vehicle *v, void *)
01807 {
01808 if (v->type == VEH_ROAD) {
01809
01810
01811
01812
01813
01814
01815 RoadVehicle *rv = RoadVehicle::From(v);
01816 if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) rv->state &= RVSB_ROAD_STOP_TRACKDIR_MASK;
01817 }
01818
01819 return NULL;
01820 }
01821
01822
01829 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags)
01830 {
01831 Station *st = Station::GetByTile(tile);
01832
01833 if (_current_company != OWNER_WATER) {
01834 CommandCost ret = CheckOwnership(st->owner);
01835 if (ret.Failed()) return ret;
01836 }
01837
01838 bool is_truck = IsTruckStop(tile);
01839
01840 RoadStop **primary_stop;
01841 RoadStop *cur_stop;
01842 if (is_truck) {
01843 primary_stop = &st->truck_stops;
01844 cur_stop = RoadStop::GetByTile(tile, ROADSTOP_TRUCK);
01845 } else {
01846 primary_stop = &st->bus_stops;
01847 cur_stop = RoadStop::GetByTile(tile, ROADSTOP_BUS);
01848 }
01849
01850 assert(cur_stop != NULL);
01851
01852
01853 if (IsDriveThroughStopTile(tile) && (flags & DC_BANKRUPT)) {
01854
01855 if (flags & DC_EXEC) FindVehicleOnPos(tile, NULL, &ClearRoadStopStatusEnum);
01856 } else {
01857 CommandCost ret = EnsureNoVehicleOnGround(tile);
01858 if (ret.Failed()) return ret;
01859 }
01860
01861 if (flags & DC_EXEC) {
01862 if (*primary_stop == cur_stop) {
01863
01864 *primary_stop = cur_stop->next;
01865
01866 if (*primary_stop == NULL) {
01867 st->facilities &= (is_truck ? ~FACIL_TRUCK_STOP : ~FACIL_BUS_STOP);
01868 }
01869 } else {
01870
01871 RoadStop *pred = *primary_stop;
01872 while (pred->next != cur_stop) pred = pred->next;
01873 pred->next = cur_stop->next;
01874 }
01875
01876 if (IsDriveThroughStopTile(tile)) {
01877
01878 cur_stop->ClearDriveThrough();
01879 } else {
01880 DoClearSquare(tile);
01881 }
01882
01883 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_ROADVEHS);
01884 delete cur_stop;
01885
01886
01887 RoadVehicle *v;
01888 FOR_ALL_ROADVEHICLES(v) {
01889 if (v->First() == v && v->current_order.IsType(OT_GOTO_STATION) &&
01890 v->dest_tile == tile) {
01891 v->dest_tile = v->GetOrderStationLocation(st->index);
01892 }
01893 }
01894
01895 st->rect.AfterRemoveTile(st, tile);
01896
01897 st->UpdateVirtCoord();
01898 st->RecomputeIndustriesNear();
01899 DeleteStationIfEmpty(st);
01900
01901
01902 if (is_truck) {
01903 st->truck_station.Clear();
01904 for (const RoadStop *rs = st->truck_stops; rs != NULL; rs = rs->next) st->truck_station.Add(rs->xy);
01905 } else {
01906 st->bus_station.Clear();
01907 for (const RoadStop *rs = st->bus_stops; rs != NULL; rs = rs->next) st->bus_station.Add(rs->xy);
01908 }
01909 }
01910
01911 return CommandCost(EXPENSES_CONSTRUCTION, _price[is_truck ? PR_CLEAR_STATION_TRUCK : PR_CLEAR_STATION_BUS]);
01912 }
01913
01924 CommandCost CmdRemoveRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01925 {
01926 uint8 width = (uint8)GB(p1, 0, 8);
01927 uint8 height = (uint8)GB(p1, 8, 8);
01928
01929
01930 if (width == 0 || height == 0) return CMD_ERROR;
01931
01932 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, height - 1) == INVALID_TILE) return CMD_ERROR;
01933
01934 TileArea roadstop_area(tile, width, height);
01935
01936 int quantity = 0;
01937 CommandCost cost(EXPENSES_CONSTRUCTION);
01938 TILE_AREA_LOOP(cur_tile, roadstop_area) {
01939
01940 if (!IsTileType(cur_tile, MP_STATION) || !IsRoadStop(cur_tile) || (uint32)GetRoadStopType(cur_tile) != GB(p2, 0, 1)) continue;
01941
01942
01943 bool is_drive_through = IsDriveThroughStopTile(cur_tile);
01944 RoadTypes rts = GetRoadTypes(cur_tile);
01945 RoadBits road_bits = IsDriveThroughStopTile(cur_tile) ?
01946 ((GetRoadStopDir(cur_tile) == DIAGDIR_NE) ? ROAD_X : ROAD_Y) :
01947 DiagDirToRoadBits(GetRoadStopDir(cur_tile));
01948
01949 Owner road_owner = GetRoadOwner(cur_tile, ROADTYPE_ROAD);
01950 Owner tram_owner = GetRoadOwner(cur_tile, ROADTYPE_TRAM);
01951 CommandCost ret = RemoveRoadStop(cur_tile, flags);
01952 if (ret.Failed()) return ret;
01953 cost.AddCost(ret);
01954
01955 quantity++;
01956
01957 if ((flags & DC_EXEC) && is_drive_through) {
01958 MakeRoadNormal(cur_tile, road_bits, rts, ClosestTownFromTile(cur_tile, UINT_MAX)->index,
01959 road_owner, tram_owner);
01960 }
01961 }
01962
01963 if (quantity == 0) return_cmd_error(STR_ERROR_THERE_IS_NO_STATION);
01964
01965 return cost;
01966 }
01967
01975 static uint GetMinimalAirportDistanceToTile(const AirportSpec *as, TileIndex town_tile, TileIndex airport_tile)
01976 {
01977 uint ttx = TileX(town_tile);
01978 uint tty = TileY(town_tile);
01979
01980 uint atx = TileX(airport_tile);
01981 uint aty = TileY(airport_tile);
01982
01983 uint btx = TileX(airport_tile) + as->size_x - 1;
01984 uint bty = TileY(airport_tile) + as->size_y - 1;
01985
01986
01987
01988
01989 uint dx = ttx < atx ? atx - ttx : (ttx <= btx ? 0 : ttx - btx);
01990 uint dy = tty < aty ? aty - tty : (tty <= bty ? 0 : tty - bty);
01991
01992 return dx + dy;
01993 }
01994
02004 uint8 GetAirportNoiseLevelForTown(const AirportSpec *as, TileIndex town_tile, TileIndex tile)
02005 {
02006
02007
02008 if (as->noise_level < 2) return as->noise_level;
02009
02010 uint distance = GetMinimalAirportDistanceToTile(as, town_tile, tile);
02011
02012
02013
02014
02015
02016 uint8 town_tolerance_distance = 8 + (_settings_game.difficulty.town_council_tolerance * 4);
02017
02018
02019
02020 uint noise_reduction = distance / town_tolerance_distance;
02021
02022
02023
02024 return noise_reduction >= as->noise_level ? 1 : as->noise_level - noise_reduction;
02025 }
02026
02034 Town *AirportGetNearestTown(const AirportSpec *as, TileIndex airport_tile)
02035 {
02036 Town *t, *nearest = NULL;
02037 uint add = as->size_x + as->size_y - 2;
02038 uint mindist = UINT_MAX - add;
02039 FOR_ALL_TOWNS(t) {
02040 if (DistanceManhattan(t->xy, airport_tile) < mindist + add) {
02041 uint dist = GetMinimalAirportDistanceToTile(as, t->xy, airport_tile);
02042 if (dist < mindist) {
02043 nearest = t;
02044 mindist = dist;
02045 }
02046 }
02047 }
02048
02049 return nearest;
02050 }
02051
02052
02054 void UpdateAirportsNoise()
02055 {
02056 Town *t;
02057 const Station *st;
02058
02059 FOR_ALL_TOWNS(t) t->noise_reached = 0;
02060
02061 FOR_ALL_STATIONS(st) {
02062 if (st->airport.tile != INVALID_TILE) {
02063 const AirportSpec *as = st->airport.GetSpec();
02064 Town *nearest = AirportGetNearestTown(as, st->airport.tile);
02065 nearest->noise_reached += GetAirportNoiseLevelForTown(as, nearest->xy, st->airport.tile);
02066 }
02067 }
02068 }
02069
02083 CommandCost CmdBuildAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02084 {
02085 StationID station_to_join = GB(p2, 16, 16);
02086 bool reuse = (station_to_join != NEW_STATION);
02087 if (!reuse) station_to_join = INVALID_STATION;
02088 bool distant_join = (station_to_join != INVALID_STATION);
02089 byte airport_type = GB(p1, 0, 8);
02090 byte layout = GB(p1, 8, 8);
02091
02092 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
02093
02094 if (airport_type >= NUM_AIRPORTS) return CMD_ERROR;
02095
02096 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
02097 if (ret.Failed()) return ret;
02098
02099
02100 const AirportSpec *as = AirportSpec::Get(airport_type);
02101 if (!as->IsAvailable() || layout >= as->num_table) return CMD_ERROR;
02102
02103 Direction rotation = as->rotation[layout];
02104 Town *t = ClosestTownFromTile(tile, UINT_MAX);
02105 int w = as->size_x;
02106 int h = as->size_y;
02107 if (rotation == DIR_E || rotation == DIR_W) Swap(w, h);
02108
02109 if (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread) {
02110 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
02111 }
02112
02113 CommandCost cost = CheckFlatLand(TileArea(tile, w, h), flags);
02114 if (cost.Failed()) return cost;
02115
02116
02117 Town *nearest = AirportGetNearestTown(as, tile);
02118 uint newnoise_level = GetAirportNoiseLevelForTown(as, nearest->xy, tile);
02119
02120
02121 StringID authority_refuse_message = STR_NULL;
02122
02123 if (_settings_game.economy.station_noise_level) {
02124
02125 if ((nearest->noise_reached + newnoise_level) > nearest->MaxTownNoise()) {
02126 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE;
02127 }
02128 } else {
02129 uint num = 0;
02130 const Station *st;
02131 FOR_ALL_STATIONS(st) {
02132 if (st->town == t && (st->facilities & FACIL_AIRPORT) && st->airport.type != AT_OILRIG) num++;
02133 }
02134 if (num >= 2) {
02135 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT;
02136 }
02137 }
02138
02139 if (authority_refuse_message != STR_NULL) {
02140 SetDParam(0, t->index);
02141 return_cmd_error(authority_refuse_message);
02142 }
02143
02144 Station *st = NULL;
02145 ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p2, 0), TileArea(tile, w, h), &st);
02146 if (ret.Failed()) return ret;
02147
02148
02149 if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
02150
02151
02152 if (st == NULL && reuse) st = GetClosestDeletedStation(tile);
02153
02154 if (st != NULL) {
02155 if (st->owner != _current_company) {
02156 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
02157 }
02158
02159 CommandCost ret = st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TEST);
02160 if (ret.Failed()) return ret;
02161
02162 if (st->airport.tile != INVALID_TILE) {
02163 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT);
02164 }
02165 } else {
02166
02167 if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
02168
02169 if (flags & DC_EXEC) {
02170 st = new Station(tile);
02171
02172 st->town = t;
02173 st->string_id = GenerateStationName(st, tile, !(GetAirport(airport_type)->flags & AirportFTAClass::AIRPLANES) ? STATIONNAMING_HELIPORT : STATIONNAMING_AIRPORT);
02174
02175 if (Company::IsValidID(_current_company)) {
02176 SetBit(st->town->have_ratings, _current_company);
02177 }
02178 }
02179 }
02180
02181 const AirportTileTable *it = as->table[layout];
02182 do {
02183 cost.AddCost(_price[PR_BUILD_STATION_AIRPORT]);
02184 } while ((++it)->ti.x != -0x80);
02185
02186 if (flags & DC_EXEC) {
02187
02188 nearest->noise_reached += newnoise_level;
02189
02190 st->AddFacility(FACIL_AIRPORT, tile);
02191 st->airport.type = airport_type;
02192 st->airport.layout = layout;
02193 st->airport.flags = 0;
02194 st->airport.rotation = rotation;
02195
02196 st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TRY);
02197
02198 it = as->table[layout];
02199 do {
02200 TileIndex cur_tile = tile + ToTileIndexDiff(it->ti);
02201 MakeAirport(cur_tile, st->owner, st->index, it->gfx, WATER_CLASS_INVALID);
02202 SetStationTileRandomBits(cur_tile, GB(Random(), 0, 4));
02203 st->airport.Add(cur_tile);
02204
02205 if (AirportTileSpec::Get(GetTranslatedAirportTileID(it->gfx))->animation.status != ANIM_STATUS_NO_ANIMATION) AddAnimatedTile(cur_tile);
02206 } while ((++it)->ti.x != -0x80);
02207
02208
02209 it = as->table[layout];
02210 do {
02211 TileIndex cur_tile = tile + ToTileIndexDiff(it->ti);
02212 AirportTileAnimationTrigger(st, cur_tile, AAT_BUILT);
02213 } while ((++it)->ti.x != -0x80);
02214
02215 UpdateAirplanesOnNewStation(st);
02216
02217 st->UpdateVirtCoord();
02218 UpdateStationAcceptance(st, false);
02219 st->RecomputeIndustriesNear();
02220 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
02221 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
02222 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_PLANES);
02223
02224 if (_settings_game.economy.station_noise_level) {
02225 SetWindowDirty(WC_TOWN_VIEW, st->town->index);
02226 }
02227 }
02228
02229 return cost;
02230 }
02231
02238 static CommandCost RemoveAirport(TileIndex tile, DoCommandFlag flags)
02239 {
02240 Station *st = Station::GetByTile(tile);
02241
02242 if (_current_company != OWNER_WATER) {
02243 CommandCost ret = CheckOwnership(st->owner);
02244 if (ret.Failed()) return ret;
02245 }
02246
02247 tile = st->airport.tile;
02248
02249 CommandCost cost(EXPENSES_CONSTRUCTION);
02250
02251 const Aircraft *a;
02252 FOR_ALL_AIRCRAFT(a) {
02253 if (!a->IsNormalAircraft()) continue;
02254 if (a->targetairport == st->index && a->state != FLYING) return CMD_ERROR;
02255 }
02256
02257 TILE_AREA_LOOP(tile_cur, st->airport) {
02258 if (!st->TileBelongsToAirport(tile_cur)) continue;
02259
02260 CommandCost ret = EnsureNoVehicleOnGround(tile_cur);
02261 if (ret.Failed()) return ret;
02262
02263 cost.AddCost(_price[PR_CLEAR_STATION_AIRPORT]);
02264
02265 if (flags & DC_EXEC) {
02266 if (IsHangarTile(tile_cur)) OrderBackup::Reset(tile_cur, false);
02267 DeleteAnimatedTile(tile_cur);
02268 DoClearSquare(tile_cur);
02269 DeleteNewGRFInspectWindow(GSF_AIRPORTTILES, tile_cur);
02270 }
02271 }
02272
02273 if (flags & DC_EXEC) {
02274 const AirportSpec *as = st->airport.GetSpec();
02275 for (uint i = 0; i < st->airport.GetNumHangars(); ++i) {
02276 DeleteWindowById(
02277 WC_VEHICLE_DEPOT, st->airport.GetHangarTile(i)
02278 );
02279 }
02280
02281
02282
02283
02284 Town *nearest = AirportGetNearestTown(as, tile);
02285 nearest->noise_reached -= GetAirportNoiseLevelForTown(as, nearest->xy, tile);
02286
02287 st->rect.AfterRemoveRect(st, st->airport);
02288
02289 st->airport.Clear();
02290 st->facilities &= ~FACIL_AIRPORT;
02291
02292 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_PLANES);
02293
02294 if (_settings_game.economy.station_noise_level) {
02295 SetWindowDirty(WC_TOWN_VIEW, st->town->index);
02296 }
02297
02298 st->UpdateVirtCoord();
02299 st->RecomputeIndustriesNear();
02300 DeleteStationIfEmpty(st);
02301 DeleteNewGRFInspectWindow(GSF_AIRPORTS, st->index);
02302 }
02303
02304 return cost;
02305 }
02306
02313 bool HasStationInUse(StationID station, bool include_company, CompanyID company)
02314 {
02315 const Vehicle *v;
02316 FOR_ALL_VEHICLES(v) {
02317 if ((v->owner == company) == include_company) {
02318 const Order *order;
02319 FOR_VEHICLE_ORDERS(v, order) {
02320 if ((order->IsType(OT_GOTO_STATION) || order->IsType(OT_GOTO_WAYPOINT)) && order->GetDestination() == station) {
02321 return true;
02322 }
02323 }
02324 }
02325 }
02326 return false;
02327 }
02328
02329 static const TileIndexDiffC _dock_tileoffs_chkaround[] = {
02330 {-1, 0},
02331 { 0, 0},
02332 { 0, 0},
02333 { 0, -1}
02334 };
02335 static const byte _dock_w_chk[4] = { 2, 1, 2, 1 };
02336 static const byte _dock_h_chk[4] = { 1, 2, 1, 2 };
02337
02347 CommandCost CmdBuildDock(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02348 {
02349 StationID station_to_join = GB(p2, 16, 16);
02350 bool reuse = (station_to_join != NEW_STATION);
02351 if (!reuse) station_to_join = INVALID_STATION;
02352 bool distant_join = (station_to_join != INVALID_STATION);
02353
02354 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
02355
02356 DiagDirection direction = GetInclinedSlopeDirection(GetTileSlope(tile, NULL));
02357 if (direction == INVALID_DIAGDIR) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02358 direction = ReverseDiagDir(direction);
02359
02360
02361 if (HasTileWaterGround(tile)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02362
02363 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
02364 if (ret.Failed()) return ret;
02365
02366 if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
02367
02368 ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02369 if (ret.Failed()) return ret;
02370
02371 TileIndex tile_cur = tile + TileOffsByDiagDir(direction);
02372
02373 if (!IsTileType(tile_cur, MP_WATER) || GetTileSlope(tile_cur, NULL) != SLOPE_FLAT) {
02374 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02375 }
02376
02377 if (MayHaveBridgeAbove(tile_cur) && IsBridgeAbove(tile_cur)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
02378
02379
02380 WaterClass wc = GetWaterClass(tile_cur);
02381
02382 ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02383 if (ret.Failed()) return ret;
02384
02385 tile_cur += TileOffsByDiagDir(direction);
02386 if (!IsTileType(tile_cur, MP_WATER) || GetTileSlope(tile_cur, NULL) != SLOPE_FLAT) {
02387 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02388 }
02389
02390
02391 Station *st = NULL;
02392 ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p1, 0),
02393 TileArea(tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
02394 _dock_w_chk[direction], _dock_h_chk[direction]), &st);
02395 if (ret.Failed()) return ret;
02396
02397
02398 if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
02399
02400
02401 if (st == NULL && reuse) st = GetClosestDeletedStation(tile);
02402
02403 if (st != NULL) {
02404 if (st->owner != _current_company) {
02405 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
02406 }
02407
02408 CommandCost ret = st->rect.BeforeAddRect(
02409 tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
02410 _dock_w_chk[direction], _dock_h_chk[direction], StationRect::ADD_TEST);
02411 if (ret.Failed()) return ret;
02412
02413 if (st->dock_tile != INVALID_TILE) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_DOCK);
02414 } else {
02415
02416 if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
02417
02418 if (flags & DC_EXEC) {
02419 st = new Station(tile);
02420
02421 st->town = ClosestTownFromTile(tile, UINT_MAX);
02422 st->string_id = GenerateStationName(st, tile, STATIONNAMING_DOCK);
02423
02424 if (Company::IsValidID(_current_company)) {
02425 SetBit(st->town->have_ratings, _current_company);
02426 }
02427 }
02428 }
02429
02430 if (flags & DC_EXEC) {
02431 st->dock_tile = tile;
02432 st->AddFacility(FACIL_DOCK, tile);
02433
02434 st->rect.BeforeAddRect(
02435 tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
02436 _dock_w_chk[direction], _dock_h_chk[direction], StationRect::ADD_TRY);
02437
02438 MakeDock(tile, st->owner, st->index, direction, wc);
02439
02440 st->UpdateVirtCoord();
02441 UpdateStationAcceptance(st, false);
02442 st->RecomputeIndustriesNear();
02443 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
02444 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
02445 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_SHIPS);
02446 }
02447
02448 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_STATION_DOCK]);
02449 }
02450
02457 static CommandCost RemoveDock(TileIndex tile, DoCommandFlag flags)
02458 {
02459 Station *st = Station::GetByTile(tile);
02460 CommandCost ret = CheckOwnership(st->owner);
02461 if (ret.Failed()) return ret;
02462
02463 TileIndex tile1 = st->dock_tile;
02464 TileIndex tile2 = tile1 + TileOffsByDiagDir(GetDockDirection(tile1));
02465
02466 ret = EnsureNoVehicleOnGround(tile1);
02467 if (ret.Succeeded()) ret = EnsureNoVehicleOnGround(tile2);
02468 if (ret.Failed()) return ret;
02469
02470 if (flags & DC_EXEC) {
02471 DoClearSquare(tile1);
02472 MarkTileDirtyByTile(tile1);
02473 MakeWaterKeepingClass(tile2, st->owner);
02474
02475 st->rect.AfterRemoveTile(st, tile1);
02476 st->rect.AfterRemoveTile(st, tile2);
02477
02478 st->dock_tile = INVALID_TILE;
02479 st->facilities &= ~FACIL_DOCK;
02480
02481 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_SHIPS);
02482 st->UpdateVirtCoord();
02483 st->RecomputeIndustriesNear();
02484 DeleteStationIfEmpty(st);
02485 }
02486
02487 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_STATION_DOCK]);
02488 }
02489
02490 #include "table/station_land.h"
02491
02492 const DrawTileSprites *GetStationTileLayout(StationType st, byte gfx)
02493 {
02494 return &_station_display_datas[st][gfx];
02495 }
02496
02497 static void DrawTile_Station(TileInfo *ti)
02498 {
02499 const DrawTileSprites *t = NULL;
02500 RoadTypes roadtypes;
02501 int32 total_offset;
02502 int32 custom_ground_offset;
02503 const RailtypeInfo *rti = NULL;
02504 uint32 relocation = 0;
02505 const BaseStation *st = NULL;
02506 const StationSpec *statspec = NULL;
02507
02508 if (HasStationRail(ti->tile)) {
02509 rti = GetRailTypeInfo(GetRailType(ti->tile));
02510 roadtypes = ROADTYPES_NONE;
02511 total_offset = rti->total_offset;
02512 custom_ground_offset = rti->custom_ground_offset;
02513
02514 if (IsCustomStationSpecIndex(ti->tile)) {
02515
02516 st = BaseStation::GetByTile(ti->tile);
02517 statspec = st->speclist[GetCustomStationSpecIndex(ti->tile)].spec;
02518
02519 if (statspec != NULL) {
02520 uint tile = GetStationGfx(ti->tile);
02521
02522 relocation = GetCustomStationRelocation(statspec, st, ti->tile);
02523
02524 if (HasBit(statspec->callback_mask, CBM_STATION_SPRITE_LAYOUT)) {
02525 uint16 callback = GetStationCallback(CBID_STATION_SPRITE_LAYOUT, 0, 0, statspec, st, ti->tile);
02526 if (callback != CALLBACK_FAILED) tile = (callback & ~1) + GetRailStationAxis(ti->tile);
02527 }
02528
02529
02530 if (statspec->renderdata != NULL) {
02531 t = &statspec->renderdata[tile < statspec->tiles ? tile : (uint)GetRailStationAxis(ti->tile)];
02532 }
02533 }
02534 }
02535 } else {
02536 roadtypes = IsRoadStop(ti->tile) ? GetRoadTypes(ti->tile) : ROADTYPES_NONE;
02537 total_offset = 0;
02538 custom_ground_offset = 0;
02539 }
02540
02541 if (IsAirport(ti->tile)) {
02542 StationGfx gfx = GetAirportGfx(ti->tile);
02543 if (gfx >= NEW_AIRPORTTILE_OFFSET) {
02544 const AirportTileSpec *ats = AirportTileSpec::Get(gfx);
02545 if (ats->grf_prop.spritegroup[0] != NULL && DrawNewAirportTile(ti, Station::GetByTile(ti->tile), gfx, ats)) {
02546 return;
02547 }
02548
02549
02550 assert(ats->grf_prop.subst_id != INVALID_AIRPORTTILE);
02551 gfx = ats->grf_prop.subst_id;
02552 }
02553 switch (gfx) {
02554 case APT_RADAR_GRASS_FENCE_SW:
02555 t = &_station_display_datas_airport_radar_grass_fence_sw[GetAnimationFrame(ti->tile)];
02556 break;
02557 case APT_GRASS_FENCE_NE_FLAG:
02558 t = &_station_display_datas_airport_flag_grass_fence_ne[GetAnimationFrame(ti->tile)];
02559 break;
02560 case APT_RADAR_FENCE_SW:
02561 t = &_station_display_datas_airport_radar_fence_sw[GetAnimationFrame(ti->tile)];
02562 break;
02563 case APT_RADAR_FENCE_NE:
02564 t = &_station_display_datas_airport_radar_fence_ne[GetAnimationFrame(ti->tile)];
02565 break;
02566 case APT_GRASS_FENCE_NE_FLAG_2:
02567 t = &_station_display_datas_airport_flag_grass_fence_ne_2[GetAnimationFrame(ti->tile)];
02568 break;
02569 }
02570 }
02571
02572 Owner owner = GetTileOwner(ti->tile);
02573
02574 PaletteID palette;
02575 if (Company::IsValidID(owner)) {
02576 palette = COMPANY_SPRITE_COLOUR(owner);
02577 } else {
02578
02579 palette = PALETTE_TO_GREY;
02580 }
02581
02582 if (t == NULL || t->seq == NULL) t = GetStationTileLayout(GetStationType(ti->tile), GetStationGfx(ti->tile));
02583
02584
02585 if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile)) {
02586 if (statspec != NULL && HasBit(statspec->flags, SSF_CUSTOM_FOUNDATIONS)) {
02587
02588 SpriteID image = GetCustomStationFoundationRelocation(statspec, st, ti->tile);
02589
02590 if (HasBit(statspec->flags, SSF_EXTENDED_FOUNDATIONS)) {
02591
02592
02593 static const uint8 foundation_parts[] = {
02594 0, 0, 0, 0,
02595 0, 1, 2, 3,
02596 0, 4, 5, 6,
02597 7, 8, 9
02598 };
02599
02600 AddSortableSpriteToDraw(image + foundation_parts[ti->tileh], PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
02601 } else {
02602
02603
02604
02605
02606 static const uint8 composite_foundation_parts[] = {
02607
02608 0x00, 0xD1, 0xE4, 0xE0,
02609
02610 0xCA, 0xC9, 0xC4, 0xC0,
02611
02612 0xD2, 0x91, 0xE4, 0xA0,
02613
02614 0x4A, 0x09, 0x44
02615 };
02616
02617 uint8 parts = composite_foundation_parts[ti->tileh];
02618
02619
02620
02621 uint z;
02622 Slope slope = GetFoundationSlope(ti->tile, &z);
02623 if (!HasFoundationNW(ti->tile, slope, z)) ClrBit(parts, 6);
02624 if (!HasFoundationNE(ti->tile, slope, z)) ClrBit(parts, 7);
02625
02626 if (parts == 0) {
02627
02628
02629
02630 goto draw_default_foundation;
02631 }
02632
02633 StartSpriteCombine();
02634 for (int i = 0; i < 8; i++) {
02635 if (HasBit(parts, i)) {
02636 AddSortableSpriteToDraw(image + i, PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
02637 }
02638 }
02639 EndSpriteCombine();
02640 }
02641
02642 OffsetGroundSprite(31, 1);
02643 ti->z += ApplyFoundationToSlope(FOUNDATION_LEVELED, &ti->tileh);
02644 } else {
02645 draw_default_foundation:
02646 DrawFoundation(ti, FOUNDATION_LEVELED);
02647 }
02648 }
02649
02650 if (IsBuoy(ti->tile) || IsDock(ti->tile) || (IsOilRig(ti->tile) && IsTileOnWater(ti->tile))) {
02651 if (ti->tileh == SLOPE_FLAT) {
02652 DrawWaterClassGround(ti);
02653 } else {
02654 assert(IsDock(ti->tile));
02655 TileIndex water_tile = ti->tile + TileOffsByDiagDir(GetDockDirection(ti->tile));
02656 WaterClass wc = GetWaterClass(water_tile);
02657 if (wc == WATER_CLASS_SEA) {
02658 DrawShoreTile(ti->tileh);
02659 } else {
02660 DrawClearLandTile(ti, 3);
02661 }
02662 }
02663 } else {
02664 SpriteID image = t->ground.sprite;
02665 PaletteID pal = t->ground.pal;
02666 if (rti != NULL && rti->UsesOverlay() && (image == SPR_RAIL_TRACK_X || image == SPR_RAIL_TRACK_Y)) {
02667 SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
02668 DrawGroundSprite(SPR_FLAT_GRASS_TILE, PAL_NONE);
02669 DrawGroundSprite(ground + (image == SPR_RAIL_TRACK_X ? RTO_X : RTO_Y), PAL_NONE);
02670
02671 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationReservation(ti->tile)) {
02672 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
02673 DrawGroundSprite(overlay + (image == SPR_RAIL_TRACK_X ? RTO_X : RTO_Y), PALETTE_CRASH);
02674 }
02675 } else {
02676 if (HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE)) {
02677 image += GetCustomStationGroundRelocation(statspec, st, ti->tile);
02678 image += custom_ground_offset;
02679 } else {
02680 image += total_offset;
02681 }
02682 DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
02683
02684
02685 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationRail(ti->tile) && HasStationReservation(ti->tile)) {
02686 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
02687 DrawGroundSprite(GetRailStationAxis(ti->tile) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH);
02688 }
02689 }
02690 }
02691
02692 if (HasStationRail(ti->tile) && HasCatenaryDrawn(GetRailType(ti->tile)) && IsStationTileElectrifiable(ti->tile)) DrawCatenary(ti);
02693
02694 if (HasBit(roadtypes, ROADTYPE_TRAM)) {
02695 Axis axis = GetRoadStopDir(ti->tile) == DIAGDIR_NE ? AXIS_X : AXIS_Y;
02696 DrawGroundSprite((HasBit(roadtypes, ROADTYPE_ROAD) ? SPR_TRAMWAY_OVERLAY : SPR_TRAMWAY_TRAM) + (axis ^ 1), PAL_NONE);
02697 DrawTramCatenary(ti, axis == AXIS_X ? ROAD_X : ROAD_Y);
02698 }
02699
02700 if (IsRailWaypoint(ti->tile)) {
02701
02702 total_offset = 0;
02703 }
02704
02705 DrawRailTileSeq(ti, t, TO_BUILDINGS, total_offset, relocation, palette);
02706 }
02707
02708 void StationPickerDrawSprite(int x, int y, StationType st, RailType railtype, RoadType roadtype, int image)
02709 {
02710 int32 total_offset = 0;
02711 PaletteID pal = COMPANY_SPRITE_COLOUR(_local_company);
02712 const DrawTileSprites *t = GetStationTileLayout(st, image);
02713 const RailtypeInfo *rti = NULL;
02714
02715 if (railtype != INVALID_RAILTYPE) {
02716 rti = GetRailTypeInfo(railtype);
02717 total_offset = rti->total_offset;
02718 }
02719
02720 SpriteID img = t->ground.sprite;
02721 if ((img == SPR_RAIL_TRACK_X || img == SPR_RAIL_TRACK_Y) && rti->UsesOverlay()) {
02722 SpriteID ground = GetCustomRailSprite(rti, INVALID_TILE, RTSG_GROUND);
02723 DrawSprite(SPR_FLAT_GRASS_TILE, PAL_NONE, x, y);
02724 DrawSprite(ground + (img == SPR_RAIL_TRACK_X ? RTO_X : RTO_Y), PAL_NONE, x, y);
02725 } else {
02726 DrawSprite(img + total_offset, HasBit(img, PALETTE_MODIFIER_COLOUR) ? pal : PAL_NONE, x, y);
02727 }
02728
02729 if (roadtype == ROADTYPE_TRAM) {
02730 DrawSprite(SPR_TRAMWAY_TRAM + (t->ground.sprite == SPR_ROAD_PAVED_STRAIGHT_X ? 1 : 0), PAL_NONE, x, y);
02731 }
02732
02733
02734 DrawRailTileSeqInGUI(x, y, t, st == STATION_WAYPOINT ? 0 : total_offset, 0, pal);
02735 }
02736
02737 static uint GetSlopeZ_Station(TileIndex tile, uint x, uint y)
02738 {
02739 return GetTileMaxZ(tile);
02740 }
02741
02742 static Foundation GetFoundation_Station(TileIndex tile, Slope tileh)
02743 {
02744 return FlatteningFoundation(tileh);
02745 }
02746
02747 static void GetTileDesc_Station(TileIndex tile, TileDesc *td)
02748 {
02749 td->owner[0] = GetTileOwner(tile);
02750 if (IsDriveThroughStopTile(tile)) {
02751 Owner road_owner = INVALID_OWNER;
02752 Owner tram_owner = INVALID_OWNER;
02753 RoadTypes rts = GetRoadTypes(tile);
02754 if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
02755 if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
02756
02757
02758 if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
02759 (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
02760 uint i = 1;
02761 if (road_owner != INVALID_OWNER) {
02762 td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
02763 td->owner[i] = road_owner;
02764 i++;
02765 }
02766 if (tram_owner != INVALID_OWNER) {
02767 td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
02768 td->owner[i] = tram_owner;
02769 }
02770 }
02771 }
02772 td->build_date = BaseStation::GetByTile(tile)->build_date;
02773
02774 if (HasStationTileRail(tile)) {
02775 const StationSpec *spec = GetStationSpec(tile);
02776
02777 if (spec != NULL) {
02778 td->station_class = StationClass::GetName(spec->cls_id);
02779 td->station_name = spec->name;
02780
02781 if (spec->grf_prop.grffile != NULL) {
02782 const GRFConfig *gc = GetGRFConfig(spec->grf_prop.grffile->grfid);
02783 td->grf = gc->GetName();
02784 }
02785 }
02786
02787 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
02788 td->rail_speed = rti->max_speed;
02789 }
02790
02791 if (IsAirport(tile)) {
02792 const AirportSpec *as = Station::GetByTile(tile)->airport.GetSpec();
02793 td->airport_class = AirportClass::GetName(as->cls_id);
02794 td->airport_name = as->name;
02795
02796 const AirportTileSpec *ats = AirportTileSpec::GetByTile(tile);
02797 td->airport_tile_name = ats->name;
02798
02799 if (as->grf_prop.grffile != NULL) {
02800 const GRFConfig *gc = GetGRFConfig(as->grf_prop.grffile->grfid);
02801 td->grf = gc->GetName();
02802 } else if (ats->grf_prop.grffile != NULL) {
02803 const GRFConfig *gc = GetGRFConfig(ats->grf_prop.grffile->grfid);
02804 td->grf = gc->GetName();
02805 }
02806 }
02807
02808 StringID str;
02809 switch (GetStationType(tile)) {
02810 default: NOT_REACHED();
02811 case STATION_RAIL: str = STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION; break;
02812 case STATION_AIRPORT:
02813 str = (IsHangar(tile) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR : STR_LAI_STATION_DESCRIPTION_AIRPORT);
02814 break;
02815 case STATION_TRUCK: str = STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA; break;
02816 case STATION_BUS: str = STR_LAI_STATION_DESCRIPTION_BUS_STATION; break;
02817 case STATION_OILRIG: str = STR_INDUSTRY_NAME_OIL_RIG; break;
02818 case STATION_DOCK: str = STR_LAI_STATION_DESCRIPTION_SHIP_DOCK; break;
02819 case STATION_BUOY: str = STR_LAI_STATION_DESCRIPTION_BUOY; break;
02820 case STATION_WAYPOINT: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
02821 }
02822 td->str = str;
02823 }
02824
02825
02826 static TrackStatus GetTileTrackStatus_Station(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
02827 {
02828 TrackBits trackbits = TRACK_BIT_NONE;
02829
02830 switch (mode) {
02831 case TRANSPORT_RAIL:
02832 if (HasStationRail(tile) && !IsStationTileBlocked(tile)) {
02833 trackbits = TrackToTrackBits(GetRailStationTrack(tile));
02834 }
02835 break;
02836
02837 case TRANSPORT_WATER:
02838
02839 if (IsBuoy(tile)) {
02840 trackbits = TRACK_BIT_ALL;
02841
02842 if (TileX(tile) == 0) trackbits &= ~(TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT);
02843
02844 if (TileY(tile) == 0) trackbits &= ~(TRACK_BIT_Y | TRACK_BIT_LEFT | TRACK_BIT_UPPER);
02845 }
02846 break;
02847
02848 case TRANSPORT_ROAD:
02849 if ((GetRoadTypes(tile) & sub_mode) != 0 && IsRoadStop(tile)) {
02850 DiagDirection dir = GetRoadStopDir(tile);
02851 Axis axis = DiagDirToAxis(dir);
02852
02853 if (side != INVALID_DIAGDIR) {
02854 if (axis != DiagDirToAxis(side) || (IsStandardRoadStopTile(tile) && dir != side)) break;
02855 }
02856
02857 trackbits = AxisToTrackBits(axis);
02858 }
02859 break;
02860
02861 default:
02862 break;
02863 }
02864
02865 return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits), TRACKDIR_BIT_NONE);
02866 }
02867
02868
02869 static void TileLoop_Station(TileIndex tile)
02870 {
02871
02872
02873 switch (GetStationType(tile)) {
02874 case STATION_AIRPORT:
02875 AirportTileAnimationTrigger(Station::GetByTile(tile), tile, AAT_TILELOOP);
02876 break;
02877
02878 case STATION_DOCK:
02879 if (GetTileSlope(tile, NULL) != SLOPE_FLAT) break;
02880
02881 case STATION_OILRIG:
02882 case STATION_BUOY:
02883 TileLoop_Water(tile);
02884 break;
02885
02886 default: break;
02887 }
02888 }
02889
02890
02891 static void AnimateTile_Station(TileIndex tile)
02892 {
02893 if (HasStationRail(tile)) {
02894 AnimateStationTile(tile);
02895 return;
02896 }
02897
02898 if (IsAirport(tile)) {
02899 AnimateAirportTile(tile);
02900 }
02901 }
02902
02903
02904 static bool ClickTile_Station(TileIndex tile)
02905 {
02906 const BaseStation *bst = BaseStation::GetByTile(tile);
02907
02908 if (bst->facilities & FACIL_WAYPOINT) {
02909 ShowWaypointWindow(Waypoint::From(bst));
02910 } else if (IsHangar(tile)) {
02911 const Station *st = Station::From(bst);
02912 ShowDepotWindow(st->airport.GetHangarTile(st->airport.GetHangarNum(tile)), VEH_AIRCRAFT);
02913 } else {
02914 ShowStationViewWindow(bst->index);
02915 }
02916 return true;
02917 }
02918
02919 static VehicleEnterTileStatus VehicleEnter_Station(Vehicle *v, TileIndex tile, int x, int y)
02920 {
02921 if (v->type == VEH_TRAIN) {
02922 StationID station_id = GetStationIndex(tile);
02923 if (!v->current_order.ShouldStopAtStation(v, station_id)) return VETSB_CONTINUE;
02924 if (!IsRailStation(tile) || !v->IsFrontEngine()) return VETSB_CONTINUE;
02925
02926 int station_ahead;
02927 int station_length;
02928 int stop = GetTrainStopLocation(station_id, tile, Train::From(v), &station_ahead, &station_length);
02929
02930
02931
02932
02933
02934 if (!IsInsideBS(stop + station_ahead, station_length, TILE_SIZE)) return VETSB_CONTINUE;
02935
02936 DiagDirection dir = DirToDiagDir(v->direction);
02937
02938 x &= 0xF;
02939 y &= 0xF;
02940
02941 if (DiagDirToAxis(dir) != AXIS_X) Swap(x, y);
02942 if (y == TILE_SIZE / 2) {
02943 if (dir != DIAGDIR_SE && dir != DIAGDIR_SW) x = TILE_SIZE - 1 - x;
02944 stop &= TILE_SIZE - 1;
02945
02946 if (x == stop) return VETSB_ENTERED_STATION | (VehicleEnterTileStatus)(station_id << VETS_STATION_ID_OFFSET);
02947 if (x < stop) {
02948 uint16 spd;
02949
02950 v->vehstatus |= VS_TRAIN_SLOWING;
02951 spd = max(0, (stop - x) * 20 - 15);
02952 if (spd < v->cur_speed) v->cur_speed = spd;
02953 }
02954 }
02955 } else if (v->type == VEH_ROAD) {
02956 RoadVehicle *rv = RoadVehicle::From(v);
02957 if (rv->state < RVSB_IN_ROAD_STOP && !IsReversingRoadTrackdir((Trackdir)rv->state) && rv->frame == 0) {
02958 if (IsRoadStop(tile) && rv->IsFrontEngine()) {
02959
02960 return RoadStop::GetByTile(tile, GetRoadStopType(tile))->Enter(rv) ? VETSB_CONTINUE : VETSB_CANNOT_ENTER;
02961 }
02962 }
02963 }
02964
02965 return VETSB_CONTINUE;
02966 }
02967
02974 static bool StationHandleBigTick(BaseStation *st)
02975 {
02976 if (!st->IsInUse() && ++st->delete_ctr >= 8) {
02977 delete st;
02978 return false;
02979 }
02980
02981 if ((st->facilities & FACIL_WAYPOINT) == 0) UpdateStationAcceptance(Station::From(st), true);
02982
02983 return true;
02984 }
02985
02986 static inline void byte_inc_sat(byte *p)
02987 {
02988 byte b = *p + 1;
02989 if (b != 0) *p = b;
02990 }
02991
02992 static void UpdateStationRating(Station *st)
02993 {
02994 bool waiting_changed = false;
02995
02996 byte_inc_sat(&st->time_since_load);
02997 byte_inc_sat(&st->time_since_unload);
02998
02999 const CargoSpec *cs;
03000 FOR_ALL_CARGOSPECS(cs) {
03001 GoodsEntry *ge = &st->goods[cs->Index()];
03002
03003
03004
03005 if (!HasBit(ge->acceptance_pickup, GoodsEntry::PICKUP) && ge->rating < INITIAL_STATION_RATING) {
03006 ge->rating++;
03007 }
03008
03009
03010 if (HasBit(ge->acceptance_pickup, GoodsEntry::PICKUP)) {
03011 byte_inc_sat(&ge->days_since_pickup);
03012
03013 bool skip = false;
03014 int rating = 0;
03015 uint waiting = ge->cargo.Count();
03016
03017 if (HasBit(cs->callback_mask, CBM_CARGO_STATION_RATING_CALC)) {
03018
03019
03020
03021
03022 uint last_speed = ge->last_speed;
03023 if (last_speed == 0) last_speed = 0xFF;
03024
03025 uint32 var18 = min(ge->days_since_pickup, 0xFF) | (min(waiting, 0xFFFF) << 8) | (min(last_speed, 0xFF) << 24);
03026
03027 uint32 var10 = (st->last_vehicle_type == VEH_INVALID) ? 0x0 : (st->last_vehicle_type + 0x10);
03028 uint16 callback = GetCargoCallback(CBID_CARGO_STATION_RATING_CALC, var10, var18, cs);
03029 if (callback != CALLBACK_FAILED) {
03030 skip = true;
03031 rating = GB(callback, 0, 14);
03032
03033
03034 if (HasBit(callback, 14)) rating -= 0x4000;
03035 }
03036 }
03037
03038 if (!skip) {
03039 int b = ge->last_speed - 85;
03040 if (b >= 0) rating += b >> 2;
03041
03042 byte days = ge->days_since_pickup;
03043 if (st->last_vehicle_type == VEH_SHIP) days >>= 2;
03044 (days > 21) ||
03045 (rating += 25, days > 12) ||
03046 (rating += 25, days > 6) ||
03047 (rating += 45, days > 3) ||
03048 (rating += 35, true);
03049
03050 (rating -= 90, waiting > 1500) ||
03051 (rating += 55, waiting > 1000) ||
03052 (rating += 35, waiting > 600) ||
03053 (rating += 10, waiting > 300) ||
03054 (rating += 20, waiting > 100) ||
03055 (rating += 10, true);
03056 }
03057
03058 if (Company::IsValidID(st->owner) && HasBit(st->town->statues, st->owner)) rating += 26;
03059
03060 byte age = ge->last_age;
03061 (age >= 3) ||
03062 (rating += 10, age >= 2) ||
03063 (rating += 10, age >= 1) ||
03064 (rating += 13, true);
03065
03066 {
03067 int or_ = ge->rating;
03068
03069
03070 ge->rating = rating = or_ + Clamp(Clamp(rating, 0, 255) - or_, -2, 2);
03071
03072
03073
03074 if (rating <= 64 && waiting >= 200) {
03075 int dec = Random() & 0x1F;
03076 if (waiting < 400) dec &= 7;
03077 waiting -= dec + 1;
03078 waiting_changed = true;
03079 }
03080
03081
03082 if (rating <= 127 && waiting != 0) {
03083 uint32 r = Random();
03084 if (rating <= (int)GB(r, 0, 7)) {
03085
03086 waiting = max((int)waiting - (int)GB(r, 8, 2) - 1, 0);
03087 waiting_changed = true;
03088 }
03089 }
03090
03091
03092
03093
03094 static const uint WAITING_CARGO_THRESHOLD = 1 << 12;
03095 static const uint WAITING_CARGO_CUT_FACTOR = 1 << 6;
03096 static const uint MAX_WAITING_CARGO = 1 << 15;
03097
03098 if (waiting > WAITING_CARGO_THRESHOLD) {
03099 uint difference = waiting - WAITING_CARGO_THRESHOLD;
03100 waiting -= (difference / WAITING_CARGO_CUT_FACTOR);
03101
03102 waiting = min(waiting, MAX_WAITING_CARGO);
03103 waiting_changed = true;
03104 }
03105
03106 if (waiting_changed) ge->cargo.Truncate(waiting);
03107 }
03108 }
03109 }
03110
03111 StationID index = st->index;
03112 if (waiting_changed) {
03113 SetWindowDirty(WC_STATION_VIEW, index);
03114 } else {
03115 SetWindowWidgetDirty(WC_STATION_VIEW, index, SVW_RATINGLIST);
03116 }
03117 }
03118
03119
03120 static void StationHandleSmallTick(BaseStation *st)
03121 {
03122 if ((st->facilities & FACIL_WAYPOINT) != 0 || !st->IsInUse()) return;
03123
03124 byte b = st->delete_ctr + 1;
03125 if (b >= 185) b = 0;
03126 st->delete_ctr = b;
03127
03128 if (b == 0) UpdateStationRating(Station::From(st));
03129 }
03130
03131 void OnTick_Station()
03132 {
03133 if (_game_mode == GM_EDITOR) return;
03134
03135 BaseStation *st;
03136 FOR_ALL_BASE_STATIONS(st) {
03137 StationHandleSmallTick(st);
03138
03139
03140
03141
03142 if ((_tick_counter + st->index) % 250 == 0) {
03143
03144 if (!StationHandleBigTick(st)) continue;
03145 TriggerStationAnimation(st, st->xy, SAT_250_TICKS);
03146 if (Station::IsExpected(st)) AirportAnimationTrigger(Station::From(st), AAT_STATION_250_TICKS);
03147 }
03148
03149 if (Station::IsExpected(st)) {
03150
03151 Station *s = Station::From(st);
03152 if (s->index % DAY_TICKS == _date_fract) AgeRouteLinks(s);
03153
03154
03155 for (CargoID cid = 0; cid < NUM_CARGO; cid++) {
03156 if (s->goods[cid].cargo_counter > 0) s->goods[cid].cargo_counter--;
03157 }
03158 }
03159 }
03160 }
03161
03162 void StationMonthlyLoop()
03163 {
03164
03165 }
03166
03167
03168 void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
03169 {
03170 Station *st;
03171
03172 FOR_ALL_STATIONS(st) {
03173 if (st->owner == owner &&
03174 DistanceManhattan(tile, st->xy) <= radius) {
03175 for (CargoID i = 0; i < NUM_CARGO; i++) {
03176 GoodsEntry *ge = &st->goods[i];
03177
03178 if (ge->acceptance_pickup != 0) {
03179 ge->rating = Clamp(ge->rating + amount, 0, 255);
03180 }
03181 }
03182 }
03183 }
03184 }
03185
03186 uint UpdateStationWaiting(Station *st, CargoID type, uint amount, SourceType source_type, SourceID source_id, TileIndex dest_tile, SourceType dest_type, SourceID dest_id, OrderID next_hop, StationID next_unload, byte flags)
03187 {
03188
03189
03190 if (!CargoPacket::CanAllocateItem()) return 0;
03191
03192 GoodsEntry &ge = st->goods[type];
03193 amount += ge.amount_fract;
03194 ge.amount_fract = GB(amount, 0, 8);
03195
03196 amount >>= 8;
03197
03198 if (amount == 0) return 0;
03199
03200 ge.cargo.Append(new CargoPacket(st->index, st->xy, amount, source_type, source_id, dest_tile, dest_type, dest_id, next_hop, next_unload, flags));
03201
03202 if (!HasBit(ge.acceptance_pickup, GoodsEntry::PICKUP)) {
03203 InvalidateWindowData(WC_STATION_LIST, st->index);
03204 SetBit(ge.acceptance_pickup, GoodsEntry::PICKUP);
03205 }
03206
03207 TriggerStationAnimation(st, st->xy, SAT_NEW_CARGO, type);
03208 AirportAnimationTrigger(st, AAT_STATION_NEW_CARGO, type);
03209
03210 SetWindowDirty(WC_STATION_VIEW, st->index);
03211 st->MarkTilesDirty(true);
03212 return amount;
03213 }
03214
03215 static bool IsUniqueStationName(const char *name)
03216 {
03217 const Station *st;
03218
03219 FOR_ALL_STATIONS(st) {
03220 if (st->name != NULL && strcmp(st->name, name) == 0) return false;
03221 }
03222
03223 return true;
03224 }
03225
03235 CommandCost CmdRenameStation(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
03236 {
03237 Station *st = Station::GetIfValid(p1);
03238 if (st == NULL) return CMD_ERROR;
03239
03240 CommandCost ret = CheckOwnership(st->owner);
03241 if (ret.Failed()) return ret;
03242
03243 bool reset = StrEmpty(text);
03244
03245 if (!reset) {
03246 if (Utf8StringLength(text) >= MAX_LENGTH_STATION_NAME_CHARS) return CMD_ERROR;
03247 if (!IsUniqueStationName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
03248 }
03249
03250 if (flags & DC_EXEC) {
03251 free(st->name);
03252 st->name = reset ? NULL : strdup(text);
03253
03254 st->UpdateVirtCoord();
03255 InvalidateWindowData(WC_STATION_LIST, st->owner, 1);
03256 }
03257
03258 return CommandCost();
03259 }
03260
03267 void FindStationsAroundTiles(const TileArea &location, StationList *stations)
03268 {
03269
03270 int max_rad = (_settings_game.station.modified_catchment ? MAX_CATCHMENT : CA_UNMODIFIED);
03271
03272 for (int dy = -max_rad; dy < location.h + max_rad; dy++) {
03273 for (int dx = -max_rad; dx < location.w + max_rad; dx++) {
03274 TileIndex cur_tile = TileAddWrap(location.tile, dx, dy);
03275 if (cur_tile == INVALID_TILE || !IsTileType(cur_tile, MP_STATION)) continue;
03276
03277 Station *st = Station::GetByTile(cur_tile);
03278 if (st == NULL) continue;
03279
03280 if (_settings_game.station.modified_catchment) {
03281 int rad = st->GetCatchmentRadius();
03282 if (dx < -rad || dx >= rad + location.w || dy < -rad || dy >= rad + location.h) continue;
03283 }
03284
03285
03286
03287
03288 stations->Include(st);
03289 }
03290 }
03291 }
03292
03297 const StationList *StationFinder::GetStations()
03298 {
03299 if (this->tile != INVALID_TILE) {
03300 FindStationsAroundTiles(*this, &this->stations);
03301 this->tile = INVALID_TILE;
03302 }
03303 return &this->stations;
03304 }
03305
03306 uint MoveGoodsToStation(CargoID type, uint amount, SourceType source_type, SourceID source_id, const StationList *all_stations, TileIndex src_tile)
03307 {
03308
03309 if (amount == 0) return 0;
03310
03311
03312 if (MoveCargoWithDestinationToStation(type, &amount, source_type, source_id, all_stations, src_tile)) return amount;
03313
03314 Station *st1 = NULL;
03315 Station *st2 = NULL;
03316 uint best_rating1 = 0;
03317 uint best_rating2 = 0;
03318
03319 for (Station * const *st_iter = all_stations->Begin(); st_iter != all_stations->End(); ++st_iter) {
03320 Station *st = *st_iter;
03321
03322
03323 if (st->town->exclusive_counter > 0 && st->town->exclusivity != st->owner) continue;
03324
03325 if (st->goods[type].rating == 0) continue;
03326
03327 if (_settings_game.order.selectgoods && st->goods[type].last_speed == 0) continue;
03328
03329 if (IsCargoInClass(type, CC_PASSENGERS)) {
03330 if (st->facilities == FACIL_TRUCK_STOP) continue;
03331 } else {
03332 if (st->facilities == FACIL_BUS_STOP) continue;
03333 }
03334
03335
03336 if (st1 == NULL || st->goods[type].rating >= best_rating1) {
03337 st2 = st1; best_rating2 = best_rating1; st1 = st; best_rating1 = st->goods[type].rating;
03338 } else if (st2 == NULL || st->goods[type].rating >= best_rating2) {
03339 st2 = st; best_rating2 = st->goods[type].rating;
03340 }
03341 }
03342
03343
03344 if (st1 == NULL) return 0;
03345
03346
03347
03348 amount *= best_rating1 + 1;
03349
03350 if (st2 == NULL) {
03351
03352 return UpdateStationWaiting(st1, type, amount, source_type, source_id);
03353 }
03354
03355
03356 assert(st1 != NULL);
03357 assert(st2 != NULL);
03358 assert(best_rating1 != 0 || best_rating2 != 0);
03359
03360
03361
03362
03363
03364
03365 uint worst_cargo = amount * best_rating2 / (best_rating1 + best_rating2);
03366 assert(worst_cargo <= (amount - worst_cargo));
03367
03368
03369 uint moved = UpdateStationWaiting(st1, type, amount - worst_cargo, source_type, source_id);
03370
03371
03372 return moved + UpdateStationWaiting(st2, type, worst_cargo, source_type, source_id);
03373 }
03374
03375 void BuildOilRig(TileIndex tile)
03376 {
03377 if (!Station::CanAllocateItem()) {
03378 DEBUG(misc, 0, "Can't allocate station for oilrig at 0x%X, reverting to oilrig only", tile);
03379 return;
03380 }
03381
03382 Station *st = new Station(tile);
03383 st->town = ClosestTownFromTile(tile, UINT_MAX);
03384
03385 st->string_id = GenerateStationName(st, tile, STATIONNAMING_OILRIG);
03386
03387 assert(IsTileType(tile, MP_INDUSTRY));
03388 DeleteAnimatedTile(tile);
03389 MakeOilrig(tile, st->index, GetWaterClass(tile));
03390
03391 st->owner = OWNER_NONE;
03392 st->airport.type = AT_OILRIG;
03393 st->airport.Add(tile);
03394 st->dock_tile = tile;
03395 st->facilities = FACIL_AIRPORT | FACIL_DOCK;
03396 st->build_date = _date;
03397
03398 st->rect.BeforeAddTile(tile, StationRect::ADD_FORCE);
03399
03400 for (CargoID j = 0; j < NUM_CARGO; j++) {
03401 st->goods[j].acceptance_pickup = 0;
03402 st->goods[j].days_since_pickup = 255;
03403 st->goods[j].rating = INITIAL_STATION_RATING;
03404 st->goods[j].last_speed = 0;
03405 st->goods[j].last_age = 255;
03406 }
03407
03408 st->UpdateVirtCoord();
03409 UpdateStationAcceptance(st, false);
03410 st->RecomputeIndustriesNear();
03411 }
03412
03413 void DeleteOilRig(TileIndex tile)
03414 {
03415 Station *st = Station::GetByTile(tile);
03416
03417 MakeWaterKeepingClass(tile, OWNER_NONE);
03418
03419 st->dock_tile = INVALID_TILE;
03420 st->airport.Clear();
03421 st->facilities &= ~(FACIL_AIRPORT | FACIL_DOCK);
03422 st->airport.flags = 0;
03423
03424 st->rect.AfterRemoveTile(st, tile);
03425
03426 st->UpdateVirtCoord();
03427 st->RecomputeIndustriesNear();
03428 if (!st->IsInUse()) delete st;
03429 }
03430
03431 static void ChangeTileOwner_Station(TileIndex tile, Owner old_owner, Owner new_owner)
03432 {
03433 if (IsDriveThroughStopTile(tile)) {
03434 for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
03435
03436 if (GetRoadOwner(tile, rt) == old_owner) {
03437 SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
03438 }
03439 }
03440 }
03441
03442 if (!IsTileOwner(tile, old_owner)) return;
03443
03444 if (new_owner != INVALID_OWNER) {
03445
03446 SetTileOwner(tile, new_owner);
03447 InvalidateWindowClassesData(WC_STATION_LIST, 0);
03448 } else {
03449 if (IsDriveThroughStopTile(tile)) {
03450
03451 DoCommand(tile, 1 | 1 << 8, (GetStationType(tile) == STATION_TRUCK) ? ROADSTOP_TRUCK : ROADSTOP_BUS, DC_EXEC | DC_BANKRUPT, CMD_REMOVE_ROAD_STOP);
03452 assert(IsTileType(tile, MP_ROAD));
03453
03454 ChangeTileOwner(tile, old_owner, new_owner);
03455 } else {
03456 DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
03457
03458
03459
03460 if ((IsTileType(tile, MP_WATER) || IsBuoyTile(tile)) && IsTileOwner(tile, old_owner)) SetTileOwner(tile, OWNER_NONE);
03461 }
03462 }
03463 }
03464
03473 static bool CanRemoveRoadWithStop(TileIndex tile, DoCommandFlag flags)
03474 {
03475
03476 if (_current_company == OWNER_WATER) return true;
03477
03478 RoadTypes rts = GetRoadTypes(tile);
03479 if (HasBit(rts, ROADTYPE_TRAM)) {
03480 Owner tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
03481 if (tram_owner != OWNER_NONE && CheckOwnership(tram_owner).Failed()) return false;
03482 }
03483 if (HasBit(rts, ROADTYPE_ROAD)) {
03484 Owner road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
03485 if (road_owner != OWNER_TOWN) {
03486 if (road_owner != OWNER_NONE && CheckOwnership(road_owner).Failed()) return false;
03487 } else {
03488 if (CheckAllowRemoveRoad(tile, GetAnyRoadBits(tile, ROADTYPE_ROAD), OWNER_TOWN, ROADTYPE_ROAD, flags).Failed()) return false;
03489 }
03490 }
03491
03492 return true;
03493 }
03494
03501 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags)
03502 {
03503 if (flags & DC_AUTO) {
03504 switch (GetStationType(tile)) {
03505 default: break;
03506 case STATION_RAIL: return_cmd_error(STR_ERROR_MUST_DEMOLISH_RAILROAD);
03507 case STATION_WAYPOINT: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
03508 case STATION_AIRPORT: return_cmd_error(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST);
03509 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);
03510 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);
03511 case STATION_BUOY: return_cmd_error(STR_ERROR_BUOY_IN_THE_WAY);
03512 case STATION_DOCK: return_cmd_error(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST);
03513 case STATION_OILRIG:
03514 SetDParam(1, STR_INDUSTRY_NAME_OIL_RIG);
03515 return_cmd_error(STR_ERROR_GENERIC_OBJECT_IN_THE_WAY);
03516 }
03517 }
03518
03519 switch (GetStationType(tile)) {
03520 case STATION_RAIL: return RemoveRailStation(tile, flags);
03521 case STATION_WAYPOINT: return RemoveRailWaypoint(tile, flags);
03522 case STATION_AIRPORT: return RemoveAirport(tile, flags);
03523 case STATION_TRUCK:
03524 if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
03525 return_cmd_error(STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
03526 }
03527 return RemoveRoadStop(tile, flags);
03528 case STATION_BUS:
03529 if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
03530 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
03531 }
03532 return RemoveRoadStop(tile, flags);
03533 case STATION_BUOY: return RemoveBuoy(tile, flags);
03534 case STATION_DOCK: return RemoveDock(tile, flags);
03535 default: break;
03536 }
03537
03538 return CMD_ERROR;
03539 }
03540
03541 static CommandCost TerraformTile_Station(TileIndex tile, DoCommandFlag flags, uint z_new, Slope tileh_new)
03542 {
03543 if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
03544
03545
03546
03547 if (!IsSteepSlope(tileh_new) && (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
03548 switch (GetStationType(tile)) {
03549 case STATION_WAYPOINT:
03550 case STATION_RAIL: {
03551 DiagDirection direction = AxisToDiagDir(GetRailStationAxis(tile));
03552 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
03553 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
03554 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
03555 }
03556
03557 case STATION_AIRPORT:
03558 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
03559
03560 case STATION_TRUCK:
03561 case STATION_BUS: {
03562 DiagDirection direction = GetRoadStopDir(tile);
03563 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
03564 if (IsDriveThroughStopTile(tile)) {
03565 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
03566 }
03567 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
03568 }
03569
03570 default: break;
03571 }
03572 }
03573 }
03574 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
03575 }
03576
03577
03578 extern const TileTypeProcs _tile_type_station_procs = {
03579 DrawTile_Station,
03580 GetSlopeZ_Station,
03581 ClearTile_Station,
03582 NULL,
03583 GetTileDesc_Station,
03584 GetTileTrackStatus_Station,
03585 ClickTile_Station,
03586 AnimateTile_Station,
03587 TileLoop_Station,
03588 ChangeTileOwner_Station,
03589 NULL,
03590 VehicleEnter_Station,
03591 GetFoundation_Station,
03592 TerraformTile_Station,
03593 };