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