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