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