# waypoint_cmd.cpp

Go to the documentation of this file.

    00001 /* $Id$ */
    00002
    00003 /*
    00004  * This file is part of OpenTTD.
    00005  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
    00006  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
    00007  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
    00008  */
    00009
    00012 #include "stdafx.h"
    00013
    00014 #include "cmd_helper.h"
    00015 #include "command_func.h"
    00016 #include "landscape.h"
    00017 #include "bridge_map.h"
    00018 #include "town.h"
    00019 #include "waypoint_base.h"
    00020 #include "pathfinder/yapf/yapf_cache.h"
    00021 #include "strings_func.h"
    00022 #include "viewport_func.h"
    00023 #include "window_func.h"
    00024 #include "date_func.h"
    00025 #include "vehicle_func.h"
    00026 #include "string_func.h"
    00027 #include "company_func.h"
    00028 #include "newgrf_station.h"
    00029 #include "company_base.h"
    00030 #include "water.h"
    00031 #include "company_gui.h"
    00032
    00033 #include "table/strings.h"
    00034
    00038 void Waypoint::UpdateVirtCoord()
    00039 {
    00040   Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
    00041   SetDParam(0, this->index);
    00042   this->sign.UpdatePosition(pt.x, pt.y - 32 * ZOOM_LVL_BASE, STR_VIEWPORT_WAYPOINT);
    00043   /* Recenter viewport */
    00044   InvalidateWindowData(WC_WAYPOINT_VIEW, this->index);
    00045 }
    00046
    00054 static Waypoint *FindDeletedWaypointCloseTo(TileIndex tile, StringID str, CompanyID cid)
    00055 {
    00056   Waypoint *wp, *best = NULL;
    00057   uint thres = 8;
    00058
    00059   FOR_ALL_WAYPOINTS(wp) {
    00060     if (!wp->IsInUse() && wp->string_id == str && wp->owner == cid) {
    00061       uint cur_dist = DistanceManhattan(tile, wp->xy);
    00062
    00063       if (cur_dist < thres) {
    00064         thres = cur_dist;
    00065         best = wp;
    00066       }
    00067     }
    00068   }
    00069
    00070   return best;
    00071 }
    00072
    00080 Axis GetAxisForNewWaypoint(TileIndex tile)
    00081 {
    00082   /* The axis for rail waypoints is easy. */
    00083   if (IsRailWaypointTile(tile)) return GetRailStationAxis(tile);
    00084
    00085   /* Non-plain rail type, no valid axis for waypoints. */
    00086   if (!IsTileType(tile, MP_RAILWAY) || GetRailTileType(tile) != RAIL_TILE_NORMAL) return INVALID_AXIS;
    00087
    00088   switch (GetTrackBits(tile)) {
    00089     case TRACK_BIT_X: return AXIS_X;
    00090     case TRACK_BIT_Y: return AXIS_Y;
    00091     default:          return INVALID_AXIS;
    00092   }
    00093 }
    00094
    00095 extern CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags);
    00096
    00103 static CommandCost IsValidTileForWaypoint(TileIndex tile, Axis axis, StationID *waypoint)
    00104 {
    00105   /* if waypoint is set, then we have special handling to allow building on top of already existing waypoints.
    00106    * so waypoint points to INVALID_STATION if we can build on any waypoint.
    00107    * Or it points to a waypoint if we're only allowed to build on exactly that waypoint. */
    00108   if (waypoint != NULL && IsTileType(tile, MP_STATION)) {
    00109     if (!IsRailWaypoint(tile)) {
    00110       return ClearTile_Station(tile, DC_AUTO); // get error message
    00111     } else {
    00112       StationID wp = GetStationIndex(tile);
    00113       if (*waypoint == INVALID_STATION) {
    00114         *waypoint = wp;
    00115       } else if (*waypoint != wp) {
    00116         return_cmd_error(STR_ERROR_WAYPOINT_ADJOINS_MORE_THAN_ONE_EXISTING);
    00117       }
    00118     }
    00119   }
    00120
    00121   if (GetAxisForNewWaypoint(tile) != axis) return_cmd_error(STR_ERROR_NO_SUITABLE_RAILROAD_TRACK);
    00122
    00123   Owner owner = GetTileOwner(tile);
    00124   CommandCost ret = CheckOwnership(owner);
    00125   if (ret.Succeeded()) ret = EnsureNoVehicleOnGround(tile);
    00126   if (ret.Failed()) return ret;
    00127
    00128   Slope tileh = GetTileSlope(tile);
    00129   if (tileh != SLOPE_FLAT &&
    00130       (!_settings_game.construction.build_on_slopes || IsSteepSlope(tileh) || !(tileh & (0x3 << axis)) || !(tileh & ~(0x3 << axis)))) {
    00131     return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
    00132   }
    00133
    00134   if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
    00135
    00136   return CommandCost();
    00137 }
    00138
    00139 extern void GetStationLayout(byte *layout, int numtracks, int plat_len, const StationSpec *statspec);
    00140 extern CommandCost FindJoiningWaypoint(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Waypoint **wp);
    00141 extern CommandCost CanExpandRailStation(const BaseStation *st, TileArea &new_ta, Axis axis);
    00142
    00159 CommandCost CmdBuildRailWaypoint(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00160 {
    00161   /* Unpack parameters */
    00162   Axis axis      = Extract<Axis, 4, 1>(p1);
    00163   byte width     = GB(p1,  8, 8);
    00164   byte height    = GB(p1, 16, 8);
    00165   bool adjacent  = HasBit(p1, 24);
    00166
    00167   StationClassID spec_class = Extract<StationClassID, 0, 8>(p2);
    00168   byte spec_index           = GB(p2, 8, 8);
    00169   StationID station_to_join = GB(p2, 16, 16);
    00170
    00171   /* Check if the given station class is valid */
    00172   if (spec_class != STAT_CLASS_WAYP) return CMD_ERROR;
    00173   if (spec_index >= StationClass::Get(spec_class)->GetSpecCount()) return CMD_ERROR;
    00174
    00175   /* The number of parts to build */
    00176   byte count = axis == AXIS_X ? height : width;
    00177
    00178   if ((axis == AXIS_X ? width : height) != 1) return CMD_ERROR;
    00179   if (count == 0 || count > _settings_game.station.station_spread) return CMD_ERROR;
    00180
    00181   bool reuse = (station_to_join != NEW_STATION);
    00182   if (!reuse) station_to_join = INVALID_STATION;
    00183   bool distant_join = (station_to_join != INVALID_STATION);
    00184
    00185   if (distant_join && (!_settings_game.station.distant_join_stations || !Waypoint::IsValidID(station_to_join))) return CMD_ERROR;
    00186
    00187   /* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
    00188   StationID est = INVALID_STATION;
    00189
    00190   /* Check whether the tiles we're building on are valid rail or not. */
    00191   TileIndexDiff offset = TileOffsByDiagDir(AxisToDiagDir(OtherAxis(axis)));
    00192   for (int i = 0; i < count; i++) {
    00193     TileIndex tile = start_tile + i * offset;
    00194     CommandCost ret = IsValidTileForWaypoint(tile, axis, &est);
    00195     if (ret.Failed()) return ret;
    00196   }
    00197
    00198   Waypoint *wp = NULL;
    00199   TileArea new_location(TileArea(start_tile, width, height));
    00200   CommandCost ret = FindJoiningWaypoint(est, station_to_join, adjacent, new_location, &wp);
    00201   if (ret.Failed()) return ret;
    00202
    00203   /* Check if there is an already existing, deleted, waypoint close to us that we can reuse. */
    00204   TileIndex center_tile = start_tile + (count / 2) * offset;
    00205   if (wp == NULL && reuse) wp = FindDeletedWaypointCloseTo(center_tile, STR_SV_STNAME_WAYPOINT, _current_company);
    00206
    00207   if (wp != NULL) {
    00208     /* Reuse an existing waypoint. */
    00209     if (wp->owner != _current_company) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_WAYPOINT);
    00210
    00211     /* check if we want to expand an already existing waypoint? */
    00212     if (wp->train_station.tile != INVALID_TILE) {
    00213       CommandCost ret = CanExpandRailStation(wp, new_location, axis);
    00214       if (ret.Failed()) return ret;
    00215     }
    00216
    00217     CommandCost ret = wp->rect.BeforeAddRect(start_tile, width, height, StationRect::ADD_TEST);
    00218     if (ret.Failed()) return ret;
    00219   } else {
    00220     /* allocate and initialize new waypoint */
    00221     if (!Waypoint::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
    00222   }
    00223
    00224   if (flags & DC_EXEC) {
    00225     if (wp == NULL) {
    00226       wp = new Waypoint(start_tile);
    00227     } else if (!wp->IsInUse()) {
    00228       /* Move existing (recently deleted) waypoint to the new location */
    00229       wp->xy = start_tile;
    00230     }
    00231     wp->owner = GetTileOwner(start_tile);
    00232
    00233     wp->rect.BeforeAddRect(start_tile, width, height, StationRect::ADD_TRY);
    00234
    00235     wp->delete_ctr = 0;
    00236     wp->facilities |= FACIL_TRAIN;
    00237     wp->build_date = _date;
    00238     wp->string_id = STR_SV_STNAME_WAYPOINT;
    00239     wp->train_station = new_location;
    00240
    00241     if (wp->town == NULL) MakeDefaultName(wp);
    00242
    00243     wp->UpdateVirtCoord();
    00244
    00245     const StationSpec *spec = StationClass::Get(spec_class)->GetSpec(spec_index);
    00246     byte *layout_ptr = AllocaM(byte, count);
    00247     if (spec == NULL) {
    00248       /* The layout must be 0 for the 'normal' waypoints by design. */
    00249       memset(layout_ptr, 0, count);
    00250     } else {
    00251       /* But for NewGRF waypoints we like to have their style. */
    00252       GetStationLayout(layout_ptr, count, 1, spec);
    00253     }
    00254     byte map_spec_index = AllocateSpecToStation(spec, wp, true);
    00255
    00256     Company *c = Company::Get(wp->owner);
    00257     for (int i = 0; i < count; i++) {
    00258       TileIndex tile = start_tile + i * offset;
    00259       byte old_specindex = HasStationTileRail(tile) ? GetCustomStationSpecIndex(tile) : 0;
    00260       if (!HasStationTileRail(tile)) c->infrastructure.station++;
    00261       bool reserved = IsTileType(tile, MP_RAILWAY) ?
    00262           HasBit(GetRailReservationTrackBits(tile), AxisToTrack(axis)) :
    00263           HasStationReservation(tile);
    00264       MakeRailWaypoint(tile, wp->owner, wp->index, axis, layout_ptr[i], GetRailType(tile));
    00265       SetCustomStationSpecIndex(tile, map_spec_index);
    00266       SetRailStationReservation(tile, reserved);
    00267       MarkTileDirtyByTile(tile);
    00268
    00269       DeallocateSpecFromStation(wp, old_specindex);
    00270       YapfNotifyTrackLayoutChange(tile, AxisToTrack(axis));
    00271     }
    00272     DirtyCompanyInfrastructureWindows(wp->owner);
    00273   }
    00274
    00275   return CommandCost(EXPENSES_CONSTRUCTION, count * _price[PR_BUILD_WAYPOINT_RAIL]);
    00276 }
    00277
    00287 CommandCost CmdBuildBuoy(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00288 {
    00289   if (tile == 0 || !HasTileWaterGround(tile)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
    00290   if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
    00291
    00292   if (GetTileSlope(tile) != SLOPE_FLAT) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
    00293
    00294   /* Check if there is an already existing, deleted, waypoint close to us that we can reuse. */
    00295   Waypoint *wp = FindDeletedWaypointCloseTo(tile, STR_SV_STNAME_BUOY, OWNER_NONE);
    00296   if (wp == NULL && !Waypoint::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
    00297
    00298   CommandCost cost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_WAYPOINT_BUOY]);
    00299   if (!IsWaterTile(tile)) {
    00300     CommandCost ret = DoCommand(tile, 0, 0, flags | DC_AUTO, CMD_LANDSCAPE_CLEAR);
    00301     if (ret.Failed()) return ret;
    00302     cost.AddCost(ret);
    00303   }
    00304
    00305   if (flags & DC_EXEC) {
    00306     if (wp == NULL) {
    00307       wp = new Waypoint(tile);
    00308     } else {
    00309       /* Move existing (recently deleted) buoy to the new location */
    00310       wp->xy = tile;
    00311       InvalidateWindowData(WC_WAYPOINT_VIEW, wp->index);
    00312     }
    00313     wp->rect.BeforeAddTile(tile, StationRect::ADD_TRY);
    00314
    00315     wp->string_id = STR_SV_STNAME_BUOY;
    00316
    00317     wp->facilities |= FACIL_DOCK;
    00318     wp->owner = OWNER_NONE;
    00319
    00320     wp->build_date = _date;
    00321
    00322     if (wp->town == NULL) MakeDefaultName(wp);
    00323
    00324     MakeBuoy(tile, wp->index, GetWaterClass(tile));
    00325
    00326     wp->UpdateVirtCoord();
    00327     InvalidateWindowData(WC_WAYPOINT_VIEW, wp->index);
    00328   }
    00329
    00330   return cost;
    00331 }
    00332
    00340 CommandCost RemoveBuoy(TileIndex tile, DoCommandFlag flags)
    00341 {
    00342   /* XXX: strange stuff, allow clearing as invalid company when clearing landscape */
    00343   if (!Company::IsValidID(_current_company) && !(flags & DC_BANKRUPT)) return_cmd_error(INVALID_STRING_ID);
    00344
    00345   Waypoint *wp = Waypoint::GetByTile(tile);
    00346
    00347   if (HasStationInUse(wp->index, false, _current_company)) return_cmd_error(STR_ERROR_BUOY_IS_IN_USE);
    00348   /* remove the buoy if there is a ship on tile when company goes bankrupt... */
    00349   if (!(flags & DC_BANKRUPT)) {
    00350     CommandCost ret = EnsureNoVehicleOnGround(tile);
    00351     if (ret.Failed()) return ret;
    00352   }
    00353
    00354   if (flags & DC_EXEC) {
    00355     wp->facilities &= ~FACIL_DOCK;
    00356
    00357     InvalidateWindowData(WC_WAYPOINT_VIEW, wp->index);
    00358
    00359     /* We have to set the water tile's state to the same state as before the
    00360      * buoy was placed. Otherwise one could plant a buoy on a canal edge,
    00361      * remove it and flood the land (if the canal edge is at level 0) */
    00362     MakeWaterKeepingClass(tile, GetTileOwner(tile));
    00363
    00364     wp->rect.AfterRemoveTile(wp, tile);
    00365
    00366     wp->UpdateVirtCoord();
    00367     wp->delete_ctr = 0;
    00368   }
    00369
    00370   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_WAYPOINT_BUOY]);
    00371 }
    00372
    00378 static bool IsUniqueWaypointName(const char *name)
    00379 {
    00380   const Waypoint *wp;
    00381
    00382   FOR_ALL_WAYPOINTS(wp) {
    00383     if (wp->name != NULL && strcmp(wp->name, name) == 0) return false;
    00384   }
    00385
    00386   return true;
    00387 }
    00388
    00398 CommandCost CmdRenameWaypoint(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00399 {
    00400   Waypoint *wp = Waypoint::GetIfValid(p1);
    00401   if (wp == NULL) return CMD_ERROR;
    00402
    00403   if (wp->owner != OWNER_NONE) {
    00404     CommandCost ret = CheckOwnership(wp->owner);
    00405     if (ret.Failed()) return ret;
    00406   }
    00407
    00408   bool reset = StrEmpty(text);
    00409
    00410   if (!reset) {
    00411     if (Utf8StringLength(text) >= MAX_LENGTH_STATION_NAME_CHARS) return CMD_ERROR;
    00412     if (!IsUniqueWaypointName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
    00413   }
    00414
    00415   if (flags & DC_EXEC) {
    00416     free(wp->name);
    00417     wp->name = reset ? NULL : strdup(text);
    00418
    00419     wp->UpdateVirtCoord();
    00420   }
    00421   return CommandCost();
    00422 }